简体   繁体   English

通过单击同一单元格SWIFT中的UIButton访问自定义单元格对象属性

[英]Accessing custom cell object properties on tap of UIButton in same cell SWIFT

I have a custom cell setup with an add and subtract button, and a quantity label. 我有一个带有加减按钮和数量标签的自定义单元设置。 I'd like a label in the view controller to update with the price shown in the cell. 我希望视图控制器中的标签更新为单元格中显示的价格。

I've scoured SE and the google machine, but all examples are for Objective-C and are satisfied with passing the indexPath.row to the selector. 我已经搜索了SE和google机器,但是所有示例都是针对Objective-C的,并且对将indexPath.row传递给选择器感到满意。 I've managed to pass the row in which the add button was tapped to the selector method, however I can't access the objects in the cell, eg cell.itemNameLabel.text 我设法将点击添加按钮的行传递给选择器方法,但是我无法访问单元格中的对象,例如cell.itemNameLabel.text

I've tried implementing in the selector method something similar to the objective-c: with no joy. 我试过在选择器方法中实现类似于Objective-C的东西:没有喜悦。

UITableViewCell* cell = (UITableViewCell*)[sender superview];
NSIndexPath* indexPath = [myTableView indexPathForCell:cell];

Here is my setup: 这是我的设置:

Custom Cell: 自定义单元:

class ProductListTableViewCell: UITableViewCell {

@IBOutlet var itemNameLabel: UILabel! = UILabel()
@IBOutlet weak var itemImage: UIImageView! = UIImageView()
@IBOutlet var itemPriceLabel: UILabel! = UILabel()
@IBOutlet weak var itemQty: UILabel!
@IBOutlet weak var addItem: UIButton! = UIButton()

Main view controller: 主视图控制器:

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

    cell.itemImage.layer.cornerRadius = cell.itemImage.frame.size.width / 2
    cell.itemImage.clipsToBounds = true

    cell.addItem.tag = indexPath.row
    cell.addItem.addTarget(self, action:("cellAddItemAction:"), forControlEvents: UIControlEvents.TouchUpInside)

    cell.itemNameLabel.text = drink.objectForKey("name") as? NSString
    cell.calorieLabel.text = drink.objectForKey("calories") as? NSString

    cell.itemPriceLabel.text = drink.objectForKey("price") as? NSString
    cell.itemImage.alpha = 1

    let itemImage = drink["image"] as PFFile

    itemImage.getDataInBackgroundWithBlock{
        (imageData: NSData!, error: NSError!) -> Void in
        if error == nil {
            let image = UIImage(data: imageData)
            cell.itemImage.image = image
        }

    }
    }
)
    return cell
}

Selector method: 选择器方法:

func cellAddItemAction(sender: UIButton){

    println("pressed \(sender.tag)")

}

This works but I need to make changes to the objects in the cell, such as cell.itemQty.text. 这可行,但是我需要对单元格中的对象进行更改,例如cell.itemQty.text。

Hope this is clear, i'm quite new to programming so please be patient with my terminology, I know its not all right!! 希望这很清楚,我对编程还很陌生,所以请耐心等待我的术语,我知道这还不行!! Thanks for helping. 感谢您的帮助。

OK, so I went about it slightly differently. 好的,所以我略有不同。 This is a prototype app and needs only to appear to work. 这是一个原型应用程序,只需要显示即可使用。 Heres what I did if it helps anyone though. 如果可以帮助任何人,这就是我所做的。

Add a tag to the button being pressed in cellForRowAtIndexPath : cellForRowAtIndexPath中按下的按钮添加标签:

cell.addItem.tag = indexPath.row

Then when adding the target, instead of using Self, use the cell: 然后,在添加目标时,请使用单元格,而不是使用Self:

cell.addItem.addTarget(cell, action:("cellAddItemAction:"), forControlEvents: UIControlEvents.TouchUpInside)

Declare a global variable in the viewController: 在viewController中声明一个全局变量:

let priceUpdateKey = "com.ordr.priceUpdateKey"

Now write the function inside the cell class, and add the NSNotification method, sending your data in the userInfo parameter 现在,在单元格类中编写函数,并添加NSNotification方法,并在userInfo参数中发送数据

func cellAddItemAction(sender: UIButton){

    var count = (String(self.itemQty.text!)).toInt()!
    totalPrice = (self.itemPriceLabel!.text! as NSString).doubleValue

    count += 1

    NSNotificationCenter.defaultCenter().postNotificationName(priceUpdateKey, object: nil, userInfo: ["totalPrice":totalPrice])

}

Then back in the viewController, add an observer for the NSNotification: 然后回到viewController中,为NSNotification添加一个观察者:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "updatePrice:", name: priceUpdateKey, object: nil)

And finally write the function that the observer calls: 最后编写观察者调用的函数:

func updatePrice(sender: NSNotification) {

    let userInfo:Dictionary<String,Double!> = sender.userInfo as Dictionary<String,Double!>
    let messagePrice = userInfo["totalPrice"]
    let finalCalc = totalAmount + messagePrice!
    totalAmount = finalCalc

    totalPriceButton.setTitle("£\(totalAmount)0", forState: UIControlState.Normal)

}'

Note** I'm not claiming this is a good method, but it works for me, and if it helps you, perfect. 注意**我并不是说这是一个好方法,但是它对我有用,如果有帮助,请完善。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM