How to update a UILabel with UIButton in custom cell in Swift? - uitableview

I'm trying to implement a counter as a UILabel using + and - UIButtons in a custom cell. I've managed to reference the row using addTarget and tags for the buttons, however I'm not sure how to update the label, adding or subtracting 1 each time a button is pressed.
I've tried accessing the cell.drinkQtyLabel.text directly from the addDrink function but that clearly doesn't work. My research pointed to using delegates, but I'm not proficient enough with Xcode to know what to do with that info.
Here is a screen shot of the cells:
Here is the custom cell.swift:
import UIKit
class ProductListTableViewCell: UITableViewCell {
#IBOutlet var drinkNameLabel: UILabel! = UILabel()
#IBOutlet var drinkVesselLabel: UILabel! = UILabel()
#IBOutlet var drinkSizeLabel: UILabel! = UILabel()
#IBOutlet var drinkPriceLabel: UILabel! = UILabel()
#IBOutlet var drinkQtyLabel: UILabel! = UILabel()
#IBOutlet weak var subtractDrinkButton: UIButton! = UIButton()
#IBOutlet weak var addDrinkButton: UIButton! = UIButton()
required init(coder aDecoder: NSCoder){
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?){
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
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
}
}
and the cellForRowAtIndex method:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:ProductListTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as ProductListTableViewCell
let drink:PFObject = self.productListData.objectAtIndex(indexPath.row) as PFObject
var Qty = 1
cell.drinkNameLabel.alpha = 0
cell.drinkVesselLabel.alpha = 0
cell.drinkSizeLabel.alpha = 0
cell.drinkPriceLabel.alpha = 0
cell.drinkQtyLabel.alpha = 0
cell.drinkNameLabel.text = drink.objectForKey("name") as? NSString
cell.drinkVesselLabel.text = drink.objectForKey("vessel") as? NSString
cell.drinkSizeLabel.text = drink.objectForKey("size") as? NSString
cell.drinkPriceLabel.text = drink.objectForKey("price") as? NSString
cell.drinkQtyLabel.text = String(Qty)
UIView.animateWithDuration(0.5, animations: {
cell.drinkNameLabel.alpha = 1
cell.drinkVesselLabel.alpha = 1
cell.drinkSizeLabel.alpha = 1
cell.drinkPriceLabel.alpha = 1
cell.drinkQtyLabel.alpha = 1
})
cell.addDrinkButton.tag = indexPath.row
cell.drinkQtyLabel.tag = indexPath.row
cell.addDrinkButton.addTarget(self, action: Selector("addDrink:"), forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func addDrink(sender:UIButton){
println("Added drink in row \(sender.tag)"
//update cell.drinkQtyLabel.text
}
}
Pseudo code of what I want might look something like:
func addDrink(sender: UIButton){
for cell at indexPath(sender.tag){
cell.drinkQtyLabel.text = int(cell.drinkQtyLabel.text) + 1
}
}
But I know this isn't a solution!

Related

tableview not reading label

I am trying to update the cells on a table view but the cell is not reading the text I am passing and returning nil.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! MyCell
let item = self.items[indexPath.row]
myCell.nameLabel?.text = item as? String
print( self.items[indexPath.row])
myCell.myTableViewController = self
return myCell
}
class MyCell: UITableViewCell {
var myTableViewController: ChangeFeedViewController!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#IBOutlet weak var nameLabel: UILabel! = {
let label = UILabel()
label.text = "Any Label"
return label
}()
#IBOutlet weak var actionButton: UIButton! = {
let button = UIButton()
button.setTitle("Action", for: .normal)
return button
}()
#IBAction func buttonHandleAction(_ sender: Any) {
handelAction()
}
func handelAction(){
myTableViewController.deleteCell(cell: self)
}
}
You need to modify your outlet like this and connect to your interface builder of MyCell class.
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var actionButton: UIButton!

didSelectRowAtIndexPath not getting called when row is pressed

I have 5 custom cells in a table view but didSelectRowAtIndexPath is not working for only one cell. I have added the cell for the row at the index for that cell in the code.
let cell : FileSentCell = chatTableView.dequeueReusableCell(withIdentifier: "fileSend") as! FileSentCell
let fileUrl = self.getImageURL(forFileName: fileNameString!)
if(fileUrl == nil){
cell.downloadStatusIndicator.image = #imageLiteral(resourceName: "fileDownloadWhite")
}else{
cell.downloadStatusIndicator.image = #imageLiteral(resourceName: "downloadedWhite")
}
cell.downloadStatusIndicator.isHidden = false
cell.downloadingIndicator.alpha = 0.0
cell.sendFileView.layer.cornerRadius = 10
cell.name.text = groupMsg.senderDisplayName
cell.message.text = groupMsg.message
cell.time.text = groupMsg.dateSent!
cell.fileStatus.text = groupMsg.status
cell.fileIcon.image = returnImage(fileName:groupMsg.message!)
cell.sendFileView.tag = indexPath.row
cell.sendFileView.addGestureRecognizer(longPressGesture)
cell.sendFileView.isUserInteractionEnabled = true
return cell
I have made UITableview have a single selection. and didSelectRowAtIndexPath is getting called for all the other reuse cells except for this one cell
Is there a reason or should I change some thing in the cellforat row
My FileSentCell class is
import UIKit
import QuartzCore
class FileSentCell: UITableViewCell {
#IBOutlet var sendFileView : UIView!
#IBOutlet var message : ChatLabel!
#IBOutlet var time : UILabel!
#IBOutlet var fileStatus : UILabel!
#IBOutlet var fileIcon : UIImageView!
#IBOutlet var downloadStatusIndicator : UIImageView!
#IBOutlet var downloadingIndicator: UIActivityIndicatorView!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init(coder aDecoder: NSCoder) {
//fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)!
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
One more thing is if I reduce the width of UIView inside content view and click the row where UIView is not being displayed didSelectRow is getting called, So didSelectRow is not getting called only when it is clicked on the UIView inside content View
Thanks in Advance.
Set:
cell.contentView.isUserInteractionEnabled = true

Swift 2 can not add a slider to a UITableView Cell

I m trying to create a slider cell in a UItableview with swift, it appear, but it's not working, I want to display the value of it in live but it's not working, I tried to use action on the slider itself, I tried changed Editing Changed Method not working too.
Here is my cell code :
import UIKit
class SliderCell: UITableViewCell {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var maxLegendLabel: UILabel!
#IBOutlet weak var minLegendLabel: UILabel!
#IBOutlet weak var slider: UISlider!
#IBOutlet weak var answerLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
slider.userInteractionEnabled = true
slider.continuous = true
// slider.addTarget(self, action: #selector(sliderValueChanged), forControlEvents: UIControlEvents.ValueChanged)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func sliderAction(sender: UISlider) {
print("slider ACTION value")
print(sender.value)
}
func sliderValueChanged(sender: UISlider) {
print("slider value")
print(sender.value)
answerLabel.text = "Your choice : " + String(sender.value)
}
func displayBlock(block: Block){
titleLabel.text = block.title
minLegendLabel.text = block.range?.legendMin
maxLegendLabel.text = block.range?.legendMax
slider.minimumValue = Float((block.range?.min)!)!
slider.maximumValue = Float((block.range?.max)!)!
slider.value = 1
}
}
and here is how I declare it in my tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell method :
let cell = tableView.dequeueReusableCellWithIdentifier(CurrentFormTableView.CellIdentifiers.SliderCell, forIndexPath: indexPath) as! SliderCell
cell.displayQuestion(block)
cell.selectionStyle = UITableViewCellSelectionStyle.None
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 160.0
return cell
Add this in Table view cell:
sliderDemo = UISlider(frame:CGRectMake(0, 0, 200,20))
var numberOfSteps : NSInteger = numbers.count - 1
sliderDemo.minimumValue = 6.5
sliderDemo.maximumValue = 4.1
sliderDemo.continuous = true
sliderDemo.value = 4.0
sliderDemo.addTarget(self, action: "sliderValueDidChange:", forControlEvents: .ValueChanged)
self.view.addSubview(sliderDemo)
func sliderValueDidChange(sender:UISlider!)
{
println("number:\(sender.value)")
}
I added the slider to the Storyboard itself and in the code I did this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MenuTableViewCell
if indexPath.row == 0 {
cell.slider.alpha = 1
} else {
cell.slider.alpha = 0
}
return cell
}
It means that it will show the slider only on the first cell, and every other cell won't show it.
Of

FirebaseUi - Cast value of UITableViewCell to custom class in swift

I can t seem to get the prototypereuseidentifier thing on firebaseUI. If I add a prototypecell, I can only give it a cellidentifier
In my following code, my IBoutlets linked to my custom cell return nil.
here s my code :
func loadData() {
self.dataSource = FirebaseTableViewDataSource(ref: refpost, cellClass: MainWitnessTableViewCell.self, cellReuseIdentifier: "<RIcell>", view: self.tableView)
self.dataSource.populateCellWithBlock { (cell: UITableViewCell, obj: NSObject) -> Void in
let snap = obj as! FDataSnapshot
print(cell)
let mycell = cell as! MainWitnessTableViewCell
let keyy: String = (snap.value.objectForKey("author") as? String)!
mycell.postContent.text = keyy
print (mycell.postContent.text)
}
self.tableView.dataSource = self.dataSource
}
here, mycell.postContent.text returns nil, is there any sorcery that keeps blinding me ? :)
sincerely
Yann
I think you should change
cellReuseIdentifier: "<RIcell>"
to
cellReuseIdentifier: "RIcell"
# jonas : here s the cell class
class MainWitnessTableViewCell: UITableViewCell, UITextFieldDelegate {
#IBOutlet weak var cellImage: UIImageView!
#IBOutlet weak var postOwner: UILabel!
#IBOutlet weak var postDate: UILabel!
#IBOutlet weak var postContent: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
postContent.text = ""
postOwner.text = ""
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}

How to alter a button in cell on click in swift ios?

I have a table layout inside a view which as a custom cell,The problem I'm facing is that the cells inside has a button i want to hide the button in cell on clicking it(only the one that is clicked should be hidden) how can i do thing in correct method?
ScrollCell.swift
class ScrollCell: UITableViewCell {
#IBOutlet weak var ProfilePic: SpringImageView!
#IBOutlet weak var UserName: SpringButton!
#IBOutlet weak var Closet: UILabel!
#IBOutlet weak var Style: UILabel!
//------//
#IBOutlet weak var MianImg: UIImageView!
//-------//
#IBOutlet weak var ProductName: UILabel!
#IBOutlet weak var LoveCount: UIButton!
#IBOutlet weak var Discount: UILabel!
#IBOutlet weak var OrginalPrice: UILabel!
#IBOutlet weak var Unliked: UIButton!
#IBOutlet weak var Liked: UIButton!
#IBOutlet weak var Comment: UIButton!
#IBOutlet weak var Share: SpringButton!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func layoutSubviews() {
ProfilePic.layer.cornerRadius = ProfilePic.bounds.height / 2
ProfilePic.clipsToBounds = true
}
}
ScrollController.swift
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1 // however many sections you need
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(try! Realm().objects(Feed))
var FeedModel = Feed()
let realm = try! Realm()
let tan = try! Realm().objects(Feed).sorted("ID", ascending: false)
return tan.count // however many rows you need
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// get an instance of your cell
cell = tableView.dequeueReusableCellWithIdentifier("ScrollCellDqueue", forIndexPath: indexPath) as! ScrollCell
IndexPath = indexPath.row
var FeedModel = Feed()
let realm = try! Realm()
let tan = try! Realm().objects(Feed).sorted("ID", ascending: false)
cell.ProfilePic.kf_setImageWithURL(NSURL(string:tan[indexPath.row].ProfilePic)!)
cell.UserName.setTitle(tan[indexPath.row].FullName, forState: .Normal)
cell.Style.text = tan[indexPath.row].StyleType
if tan[indexPath.row].UserType == "store_front"{
cell.Closet.text = "Store Front"
}else if tan[indexPath.row].UserType == "normal"{
cell.Closet.text = "Pri Loved"
}
//-----//
var SingleImage:String = ""
var ImageArray = tan[indexPath.row].ImageArraySet.componentsSeparatedByString(",")
SingleImage = ImageArray[0]
cell.MianImg.kf_setImageWithURL(NSURL(string:SingleImage)!)
//-----//
cell.ProductName.text = tan[indexPath.row].ItemName
cell.OrginalPrice?.text = "\(tan[indexPath.row].OrginalPrice)"
cell.LoveCount.setTitle("\(tan[indexPath.row].LikeCount)"+" Loves", forState: .Normal)
cell.Discount.text = "\(tan[indexPath.row].Discount)"+" % off"
if(tan[indexPath.row].LikeStatus){
cell.Unliked.hidden = true
cell.Liked.hidden = false
}
else if (!tan[indexPath.row].LikeStatus){
cell.Unliked.hidden = false
cell.Liked.hidden = true
}
cell.Unliked.tag = tan[indexPath.row].ID
cell.Liked.tag = tan[indexPath.row].ID
return cell
}
#IBAction func LikeBtn(sender: AnyObject) {
print(sender.tag)
print(IndexPath)
//here i want to know who i can hide the button i have clicked ?
}
Here i want to access the cell in which button is clicked and make changes to UI item inside that cell how can i do that ?
There are many ways to do it. One possible solution is use block.
Add this to ScrollCell
var didLikedTapped: (() -> Void)?
and receive the event of the LikedButton in the cell
#IBAction func LikeBtn(sender: AnyObject) {
didLikedTapped?()
}
Then in cellForRowAtIndexPath of viewController add this
cell.didLikedTapped = {[weak self] in
print(IndexPath)
}
Liked is uibutton in ScrollCell, i don't known, why can you add IBAction for it in ScrollController? . You must implement it in ScrollCell And code:
#IBAction func LikeBtn(sender: UIButton) {
print(sender.tag)
sender.hiden = true
}
And i think, if you have only one UIbutton, it will better. In there, like and unlike is 2 state of uibutton(seleted and none). When you click the button, change it's state
Update:
class sampleCell: UITableViewCell{
#IBOutlet var btnLike : UIButton!
#IBOutlet var btnUnLike : UIButton! // frame of 2 button is equal
override func awakeFromNib() {
super.awakeFromNib()
self.btnUnLike.hidden = true
// ...
}
func updateData(data:AnyObject){ // data's type is Feed
// set data for cell
// i think you should implement in here. and in ScollController call : cell.updateData() , it's better
/* e.x
self.ProductName.text = tan[indexPath.row].ItemName
self.OrginalPrice?.text = "\(tan[indexPath.row].OrginalPrice)"
self.LoveCount.setTitle("\(tan[indexPath.row].LikeCount)"+" Loves", forState: .Normal)
self.Discount.text = "\(tan[indexPath.row].Discount)"+" % off"
*/
}
#IBAction func likeTap(sender:UIButton){ // rememeber set outlet event for btnLike and btnUnLike is this function
if sender == self.btnLike{
self.btnLike.hidden = true
self.btnUnLike.hidden = false
// do s.t
}else if sender == self.btnUnLike{
self.btnLike.hidden = false
self.btnUnLike.hidden = true
// do s.t
}
}
}
Check if the following code help
#IBAction func LikeBtn(sender: AnyObject) {
var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(position)
let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath!)! as
UITableViewCell
print(indexPath?.row)
}
give the LikeBtn the property indexpath, in cellForRowAtIndexPath method, pass the indexPath to the LikeBtn, then you will know which cell's LikeBtn clicked.
class LikeBtn: UIButton {
var indexPath: NSIndexPath?
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// here pass the indexpath to your button
cell.likeBtn.indexPath = indexPath
return cell
}
#IBAction func likeTap(sender: LikeBtn){
if let indexPath = sender.indexPath {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
//here you will know the exact cell, now you can hide or show your buttons
}
}
}

Resources