【问题标题】:Tap on a cell affects other cell too点击一个单元格也会影响其他单元格
【发布时间】:2016-06-17 20:42:32
【问题描述】:

我正在尝试构建一个内部带有不同按钮的自定义单元格,但是当我在单元格中点击“关注按钮”并为该按钮着色时,似乎其他关注按钮也获得了颜色......另外,如果我向上滚动然后在我的 tableView 下其他按钮随机获得颜色...我仍在学习如何使用自定义单元格...

这是我的自定义单元格

class customCell: UITableViewCell
{
    @IBOutlet weak var follow: UIButton!
    @IBOutlet var comment: UIButton?
    @IBOutlet var share: UIButton? 
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{


 let cellPost = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! customCell

    cellPost.tag = Array(postToPrint.keys)[indexPath.row]

    cellPost.follow?.tag = Array(postToPrint.keys)[indexPath.row]
    cellPost.follow?.addTarget(self, action: "follow:", forControlEvents: .TouchUpInside)

    return cellaPost
    }
}

这里有我的功能关注

 func follow(sender: UIButton)
{
    let postSelected = sender.tag
    // In order to get indexPath from int values
    let indexPath = NSIndexPath(forRow: postSelected, inSection: 1)
    let cell = table.cellForRowAtIndexPath(indexPath) as! customCell
    cell.follow.setTitleColor(UIColor.redColor(), forState: UIControlState)
    idPostClicked = postSelected
    sendHttpRequest(postClicked : idPostClicked)

}

我将我的字典键作为标签给每个单元格。稍后我想将 cell.tag 作为参数发送到 sendHttpRequest 方法中。如果我将按钮功能放在我的 customCell 中,我想获取包含我的 followButton 的单元格,这样我就可以使用 cell.tag 发送请求。 但是,当我仅单击一个时,其他单元格中的文本会被着色...:/

【问题讨论】:

    标签: ios swift uitableview cocoa-touch reusability


    【解决方案1】:

    嗯,我觉得你以错误的方式处理这件事。我宁愿将func follow 移动到单元格本身。 tableView 没有理由处理这个逻辑,因为它是想要更改它可以自己访问的元素的单元格。此外,如果您将逻辑移动到单元格中,那么您将不需要 tags 或添加目标等。

    class customCell: UITableViewCell
    {
        @IBOutlet weak var follow: UIButton!
        @IBOutlet var comment: UIButton?
        @IBOutlet var share: UIButton? 
    
        // Connect the follow button to this function as an action
        @IBAction followPressed(sender: UIButton) {
            follow.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
        }
    
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        let cellPost = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! customCell
        return cellaPost
    }
    

    我相信这应该可以解决问题。

    编辑

    为按钮添加了UIControlState 的一些缺失代码。如果这不起作用,您可以上传示例项目吗?仅使用这段代码很难确定您要做什么。

    【讨论】:

    • 如何获取单击按钮所在的单元格?我需要发送一个请求 Https 传递作为参数 post 跟随
    • 添加了一个编辑。认为我将不得不查看更多代码,具体取决于您希望如何执行 HTTP 请求。
    猜你喜欢
    • 2014-09-06
    • 2019-04-11
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 2023-03-31
    • 2019-07-21
    相关资源
    最近更新 更多