简体   繁体   English

Swift 3.0 TableView单元格按钮

[英]Swift 3.0 TableView Cell Button

I have set up a button on the tableview cell and I am wondering how I can manipulate it. 我在tableview单元格上设置了一个按钮,我想知道如何操作它。 Namely, I am interested in changing the name title of the button and add another target (different capabilities of the button) to when the button is clicked. 也就是说,我有兴趣更改按钮的名称标题,并在单击按钮时添加另一个目标(按钮的不同功能)。 My thinking is that this needs to be added into the buttonClicked func, but I am not sure how to reference the specific cellForRow that was clicked. 我的想法是需要将它添加到buttonClicked func中,但我不确定如何引用被单击的特定cellForRow。 Perhaps a conditional can be used to in cellForRow that determines what the button title is? 或许可以在cellForRow中使用条件来确定按钮标题是什么? I am not too sure what the best way to go about this is. 我不太清楚最好的办法是什么。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = guestTableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 

    let button : UIButton = UIButton(type:UIButtonType.custom) as UIButton

    button.frame = CGRect(origin: CGPoint(x: 200,y :60), size: CGSize(width: 100, height: 24))
    let cellHeight: CGFloat = 44.0
    button.center = CGPoint(x: view.bounds.width / (4/3), y: cellHeight / 2.0)


    button.setTitleColor(.blue, for: .normal)
    button.addTarget(self, action: #selector(buttonClicked), for: UIControlEvents.touchUpInside)
    button.setTitle("Add", for: UIControlState.normal)

    cell.addSubview(button)


    return cell
}

func buttonClicked(sender : UIButton!) {
    print("Added!")


}

For Swift 3.2 and 4.0 对于Swift 3.2和4.0

Find " indexPath.row " and " indexPath.section " 找到“ indexPath.row ”和“ indexPath.section

//Add target on button in "cellForRowAt" //在“cellForRowAt”按钮上添加目标

cell.myBtn.addTarget(self, action: #selector(self.btnAction(_:)), for: .touchUpInside)

// Add function //添加功能

func btnAction(_ sender: UIButton) {

    let point = sender.convert(CGPoint.zero, to: yourTableView as UIView)
    let indexPath: IndexPath! = yourTableView.indexPathForRow(at: point)

    print("row is = \(indexPath.row) && section is = \(indexPath.section)")
}

Chnage And Add With Your Code Chnage并添加您的代码

    button.addTarget(self, action:#selector(YourViewController.buttonClicked(_:)), for: .touchUpInside)

    button.tag = indexPath.row



func buttonClicked(sender : UIButton!) {
    print("Added!")
     let row = sender.tag;
    print(row)

}

There are two ways you can do it - the cheat's way or the proper way. 有两种方法可以做到 - 欺骗的方式或正确的方式。 The proper was is to subclass UITableViewCell, in which case you can hookup outlets in the normal way. 正确的是子类UITableViewCell,在这种情况下,你可以正常方式连接出口。 The cheat's way is to use each element's tag property. 作弊的方法是使用每个元素的标记属性。 If you set the tag of the button to (say) 1, you can use cell.viewWithTag within cellForRowAt to locate it: As in: 如果将按钮的标记设置为(例如)1,则可以使用cellForRowAt cell.viewWithTag来定位它:如下所示:

let button = cell.viewWithTag(1) as! UIButton

Be aware that it will search the whole hierarchy below cell , so you need to ensure you don't have multiple subviews with the same tag. 请注意,它将搜索cell下方的整个层次结构,因此您需要确保没有多个具有相同标记的子视图。

From your question, I'm guessing you want to click the button and have its title changed. 从你的问题,我猜你想要点击按钮并更改其标题。 The click handler should just reload the tableView row (or whole table if you're lazy like me), and cellForRowAt needs to know what title to show. click处理程序应该只重新加载tableView行(如果你像我一样懒,那么整个表),而cellForRowAt需要知道要显示的标题。 This state of what to show on the button for each row must be held outside the tableView cell, since cells are reused as you scroll. 每个按钮上显示的内容必须保存在tableView单元格之外,因为在滚动时会重复使用单元格。 This means that once the top row scrolls off the screen that same cell might be reused for the (say) 20th row. 这意味着一旦顶行滚动屏幕,相同的单元格可能会被重复用于(例如)第20行。 The code in cellForRowAt needs to completely reset the content of the cell in case it was already used for another row. cellForRowAt的代码需要完全重置单元格的内容,以防它已被用于另一行。

Adding some detail from your comment on the question, you never want to avoid reusing cells because this is a very good thing. 从你对这个问题的评论中添加一些细节,你永远不想避免重复使用单元格,因为这是一件非常好的事情。 You might be showing a table of 1,000 rows but only 10 are visible on screen. 您可能正在显示一个包含1,000行的表,但在屏幕上只能显示10行。 Reusing cells means iOS can create as few as 10 cells to show your entire table, rather than 1,000. 重用单元格意味着iOS可以创建少至10个单元格来显示整个表格,而不是1000。 Performance is faster as a result. 结果表现更快。

In Swift 4.x , you may simply have the TableView's delegate set a tag to it, like this: Swift 4.x中 ,您可以简单地让TableView的委托为其设置标记,如下所示:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    // Assign tags
    cell.myButton.tag = indexPath.row

    return cell
}

Then connect your button from the Storyboard by right-click + drag to your .swift file as an @IBAction , select Type -> UIButton and click Connect . 然后通过右键单击+拖动到.swift文件作为@IBAction来连接故事板中的按钮,选择Type - > UIButton并单击Connect

Here's the code: 这是代码:

 @IBAction func myButt(_ sender: UIButton) {
    let buttTag = sender.tag // get the Tag of the clicked button in the Cell

    // write the code that will be called on click of your button 
 }

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

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