在Action(Swift)上的同一Tableview单元格中更改不同的按钮

时间:2016-10-24 19:12:21

标签: ios swift uitableview uibutton

每个TableView单元格中都有两个按钮。当点击一个按钮时,我想改变它的外观和另一个按钮的外观。我想出了如何使用approach outlined here更改点按按钮,但我正在努力调整其他按钮。

当前相关代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell:FeedbackTableViewCell = self.feedbackTableView.dequeueReusableCell(withIdentifier: "cell") as! FeedbackTableViewCell

    // Setup YES / NO Buttons
    cell.feedbackYesButton.addTarget(self, action: #selector(MainSearchViewController.feedbackYesButtonTapped(sender:)), for: .touchUpInside)
    cell.feedbackNoButton.addTarget(self, action: #selector(MainSearchViewController.feedbackNoButtonTapped(sender:)), for: .touchUpInside)

    cell.feedbackYesButton.tag = indexPath.row
    cell.feedbackNoButton.tag = indexPath.row

    return cell
}


func feedbackYesButtonTapped (sender:UIButton) {

    let yesButtonTag = sender.tag

    switch yesButtonTag {
    case 0:

        // If YES button was not selected or was NO, then save value as YES and turn button "on", plus turn NO button "off".
            turnFeedbackButtonOn(sender)
            turnFeedbackButtonOff(NOT SURE HOW TO HANDLE THIS?)
        }
    // Other cases handled accordingly.
    default:
        return
    }
}

//MARK: - Functions to change the appearances of feedback buttons 
func turnFeedbackButtonOn(_ button: UIButton) {

    button.setTitleColor(UIColor(red: 157/255, green: 249/255, blue: 88/255, alpha: 1 ), for: UIControlState())
    button.titleLabel?.font = UIFont(name: "Avenir-Black", size: 18)
}

func turnFeedbackButtonOff(_ button: UIButton) {

    button.setTitleColor(UIColor.black, for: UIControlState())
    button.titleLabel?.font = UIFont(name: "Avenir", size: 17)
}

我尝试使用目标按钮传递另一个按钮,但尝试此操作时出错。感觉这应该有用,但我不是Swift的专家所以非常感谢任何帮助!

cell.feedbackYesButton.addTarget(self, action: #selector(MainSearchViewController.feedbackYesButtonTapped(cell.feedbackYesButton, otherButton:cell.feedbackNoButton)), for: .touchUpInside)

func feedbackYesButtonTapped (sender:UIButton, otherButton:UIButton) {

//...

}

1 个答案:

答案 0 :(得分:1)

如果您处理UITableViewCell类中的按钮事件会更容易一些,因为您可以轻松地引用其中的两个按钮,但仍然可以按照您的方式执行您想要的操作这样做:

首先,您需要在按下按钮后获取对单元格的引用。看起来你将单元格的行设置为按钮的标记,所以我假设你在该tableView中只有1个部分。在这种情况下,您可以通过说let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: button.tag, inSection: 0))来获取对单元格的引用。由于显而易见的原因,这将返回一个可选项,因此您需要确保安全地打开它。然后你可以在你不确定如何处理它的地方说turnFeedbackButtonOff(cell.feedbackNoButton)

相关问题