Access custom UITableViewCell from random func in swift 3 - xcode

I have a custom UITableViewCell, where i am trying to change the cell.indicatorLabel background color from a func, but i do not know how to access the cell from that func
class mainCell: UITableViewCell {
#IBOutlet weak var barcodeLabel: UILabel!
#IBOutlet weak var indicatorLabel: UILabel!
}
and i have a func called
func scan() {}
my cellForRowAt looks like this
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? mainCell
cell?.barcodeLabel.text = barcodeArray[indexPath.row].Barcode
cell?.indicatorLabel.text = barcodeArray[indexPath.row].Indicator
return cell!
}
i like to change the background color of the label from my func, anyone who can help with this?

Related

Prototype Cell width runs off the page in a Table View

Fairly new to coding and this is my first post here. I added a Prototype Cell to a Table View Cell but when I run the project the cell runs off the page (on the right)? Does anyone have any help they can provide?
This is the ViewController code:
import UIKit
class ConsultationsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
ConsultationFunctions.readConsultations(completion: { [weak self] in
self?.tableView.reloadData()
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Data.consultationModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ConsutationsTableViewCell
cell.setup(consultationModel: Data.consultationModels[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
And this is the TableViewController code:
import UIKit
class ConsutationsTableViewCell: UITableViewCell {
#IBOutlet weak var cardView: UIView!
#IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
cardView.layer.shadowOffset = CGSize.zero
cardView.layer.shadowColor = UIColor.systemBlue.cgColor
cardView.layer.cornerRadius = 10
}
func setup(consultationModel: ConsultationModel) {
titleLabel.text = consultationModel.title
}
}
I've tried adjusting the Storyboards Identity, Attributes and Size Inspectors as best I can but just don't understand where I've gone wrong? Any guidance is greatly appreciated
I don't see the interface constraints in your code, so I guess you have them in the Storyboard, or ar least you should.
I suggest you to go through some tutorials or guides to "Add New Constraints" for cardView and titleLabel. Here you have a simple one:
https://www.ralfebert.de/ios-examples/uikit/uitableviewcontroller/custom-cells/

swift 3 change uitableviewcell after click uitableviewcell from another view controller?

I am trying to make my tableview cell from viewcontroller 1 change when the user click on a cell from tableview cell from viewcontroller 2. I know that I have to work with the function
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
however, I am not sure how I would accomplish what I wanted.
Here's my code:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = changeHotelTableView.indexPathForSelectedRow;
let currentCell = changeHotelTableView.cellForRow(at: indexPath!) as! ChangeHotelTableViewCell
var valueToPass = currentCell.textLabel?.text
}
I want to get the valueToPass variable into my cell at another' view controller; say this is called timeViewController with timeTableView and a timeTableViewCell. How will I do this?
Thanks for your help and time in advance
Perhaps you should try with Protocol.
ViewController2:
protocol UserPressTheCell: NSObjectProtocol
{
func didUserPressTheCellWith(indexPath: IndexPath, text: String)
}
class ViewController2: UIViewController
{
//declare delegate
weak var delegate: UserPressTheCell?
....
func tableview(_ tableview: UITableView, didSelectRowAt indexPath: IndexPath)
{
let indexPath = changeHotelTableView.indexPathForSelectedRow;
let currentCell = changeHotelTableView.cellForRow(at: indexPath!) as! ChangeHotelTableViewCell
self.delegate?.didUserPressTheCellWith(indexPath: indexPath, text: currentCell.textLabel?.text)
}
}
Then implement in ViewController1:
class ViewController1: UIViewController, UserPressTheCell
{
#IBOutlet weak var tableview: UITableView!
...
//MARK: UserPressTheCell
func didUserPressTheCellWith(indexPath: IndexPath, text: String)
{
let cell = self.tableView.cellForRow(at: indexPath!) as! "Your VC1's cell"
cell.textLabel?.text = text
}
}
To be sure delegate will not be nil:
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
let vc2 = segue.destination as! ViewController2
vc2.delegate = self
}
or wherever you segue to ViewController2.
Maybe this is the best way to accomplish what you wanted.

pass data between two UITableView with custom cell

I'm going to pass data from a UITableViewController to another UITableViewController. These two UITableViewController have custom cell in it.
When I pass the data by segue, I can't get the data from sourceViewController as it says that there's no member of the label I built in the Custom UITableViewCell controller.
Main Problem that find no member in menuController. Do I need to inherit or delegate the custom cell to menuController or push it?
Here is the code of ordersController:
import UIKit
struct Order {
var tilte:String
var price:String
var quantity:String
}
class ordersController: UITableViewController {
var orders = Array<Order>()
override func viewDidLoad() {
super.viewDidLoad()
}
//handle exit from Cancel back of menuController
#IBAction func cancelBack(segue: UIStoryboardSegue){
}
//handle exit from Done back of menuController
#IBAction func doneBack(segue: UIStoryboardSegue){
print("Done and Back")
//let source = segue.sourceViewController as! newMenu
//let quantity = source.burgerQuan.text
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.orders.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("orderedItem", forIndexPath: indexPath) as! ordersCustomCell
let order:Order = self.orders[indexPath.row]
cell.ordersName.text = orders[indexPath.row].title
cell.ordersPrice.text = orders[indexPath.row].price
cell.ordersQuantity.text = orders[indexPath.row].quantity
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Here is code of Custom Cell of ordersController:
class ordersCustomCell: UITableViewCell {
#IBOutlet weak var ordersName: UILabel!
#IBOutlet weak var ordersPrice: UILabel!
#IBOutlet weak var ordersQuantity: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
Here is the code of menuController:
class menuController: UITableViewController {
var items:[String] = ["Hamburger","French Fries", "Coffee", "Lemon Tea"]
var price:[String] = ["$29", "$13", "$25", "$8"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("menuItem", forIndexPath: indexPath) as! menuCustomCell
cell.menuName.text = self.items[indexPath.row]
cell.menuPrice.text = self.price[indexPath.row]
return cell
}
}
And here is code of custom cell of menuController:
class menuCustomCell: UITableViewCell {
#IBOutlet weak var menuName: UILabel!
#IBOutlet weak var menuPrice: UILabel!
#IBOutlet weak var menuQuantity: UILabel!
#IBOutlet weak var stepper: UIStepper!
#IBAction func stepperValueChanged(sender: UIStepper) {
menuQuantity.text = Int(sender.value).description
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
How can I do this? --> When the Add button in Orders is clicked, it shows the Menu. User click the stepper to select the quantity. Then, data pass back to Orders when user click Done. The items which quantity is not 0 will be shown on the list on Orders.
Your menuController class does not that that variable menuName, thats why it cannot find it.
All you have is items and price in that view controller.
You have menuName within your custom cell. That is different from the viewController you are pushing too.

UIImageView in table cell is not staying within frame original frame?

So this is what is happening:
I've added a red background color to the image view so you can see how much it's going over.
I've tried tableView(:willDisplayHeaderView:), I've tried checking off Subviews, I've tried AspectFit, AspectFill, & ScaletoFill But the UIImageView's keep going beyond their original boundaries and I don't understand why.
Here's some code from my UITableViewController:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("scheduleCell", forIndexPath: indexPath) as! ScheduleTableViewCell
let eventList = schedule?.schedule[dayOfWeek[indexPath.section]]!
let event = eventList![indexPath.row]
cell.labelEvent.text = event.act.rawValue
cell.labelTime.text = "\(event.getTime(event.start)) - \(event.getTime(event.end))"
return cell
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let tableViewCell = cell as! ScheduleTableViewCell
let eventList = schedule?.schedule[dayOfWeek[indexPath.section]]!
let event = eventList![indexPath.row]
tableViewCell.imageView?.image = UIImage(named: "\(schedule!.potato.mode)-\(event.act.rawValue)")
tableViewCell.imageView?.backgroundColor = UIColor.redColor()
tableViewCell.imageView?.contentMode = .ScaleAspectFit
}
And this is my custom cell class:
class ScheduleTableViewCell: UITableViewCell {
#IBOutlet weak var imageEvent: UIImageView!
#IBOutlet weak var labelEvent: UILabel!
#IBOutlet weak var labelTime: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
First, setting the imageView's clipsToBounds property to true will prevent the image from spilling over the bounds of the imageView.
Second, the image is clearly bigger than the imageView, so I think the imageView is not spilling over, the image inside it is spilling over. So, you will either need to resize the image or use Scale*Fill modes to show the full image or crop it as appropriate.
HTH.

How to transfer data from table cell to a new view controller using prepare for segue method?

How to use prepare for segue to transfer the images (tweetImg) and date (dateLbl) from tablecell (mainCell) to the Newviewcontroller when I select the cell? in my case I am using parse.com as my backend to retrieve the images and dates data. I am new to programming would appreciate some help, thank you.
mainVC
import UIKit
class mainVC: UIViewController, UITableViewDataSource, UITableViewDelegate, {
#IBOutlet weak var resultsTable: UITableView!
var resultsStartdateArray = [String]()
var resultsTweetImageFiles = [PFFile?]()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsTweetImageFiles.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 350
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:mainCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! mainCell
cell.dateLbl.text = self.resultsStartdateArray[indexPath.row]
resultsTweetImageFiles[indexPath.row]?.getDataInBackgroundWithBlock({
(imageData:NSData?, error:NSError?) -> Void in
if error == nil {
let image = UIImage(data: imageData!)
cell.tweetImg.image = image
}
})
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("SendDataSegue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if (segue.identifier == "SendDataSegue")
{
let destination: NewViewController = segue.destinationViewController as! NewViewController
// I believe the missing code should be here
}
}
}
mainCell
import UIKit
class mainCell: UITableViewCell {
#IBOutlet weak var tweetImg: UIImageView!
#IBOutlet weak var dateLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
}
NewViewController
import UIKit
class NewViewController: UIViewController {
#IBOutlet weak var dateLbl: UILabel!
#IBOutlet weak var tweetImg: UIImageView!
var titleString: String!
override func viewDidLoad()
{
super.viewDidLoad()
self.dateLbl.text = self.titleString
}
Bellow i have mentioned a sample template code. organize your code according to bellow mentioned code. important part is select a cell in the prepareForSegue instead of in didSelectRowAtIndexPath. Which is let IndexPath = self.tableView.indexPathForSelectedRow()!
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//Index path is the selected cell
let IndexPath = self.tableView.indexPathForSelectedRow()!
//Here you can assign your tweetImg and dateLbl
let newViewController = segue.destinationViewController as! NewViewController
newViewController.dateLbl.text = //your date label value
//here assign your image to destination view controller property
}
Delete the method didSelectRowAtIndexPath and connect the segue to the table view cell rather than the view controller.
When a cell is selected it's passed as the sender parameter in the prepareForSegue method.
A side note : Don't perform background tasks in the view – the cellForRowAtIndexPath method – , do it in the model – the items in the data source array – and then call reloadData()

Resources