如何在UITableViewCell上突出显示UIButton

时间:2018-12-03 14:34:01

标签: ios swift uitableview uicolor

如何在单击时设置UIButton高亮,请帮助我,因为我完全陷入了这段代码中

func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
    let cell = self.leaveDetailTableView.cellForRow(at: indexPath) as? LeaveDetailCell
    cell!.cellCardView.backgroundColor = #colorLiteral(red: 0.9568627451, green: 0.8941176471, blue: 0.6549019608, alpha: 1)
}

func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
    let cell = self.leaveDetailTableView.cellForRow(at: indexPath) as? LeaveDetailCell
    cell!.cellCardView.backgroundColor = UIColor.white
}

当我选择一个表格视图项时,我必须用颜色突出显示特定的行,我想选择自己的颜色。

2 个答案:

答案 0 :(得分:0)

如果要在单击按钮时更改颜色,可以执行以下操作 首先,您应该在按钮上添加一个操作

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
cell.cellCardView.addGestureRecognizer(tapGesture)

执行此操作后,在操作handleTapGesture(_:)中,您可以像这样更改按钮的颜色

func handleTapGesture(_ sender: UIButton) {
    UIView.animate(withDuration: 0.1, animations: {
        sender.backgroundColor = #colorLiteral(red: 0.9568627451, green: 0.8941176471, blue: 0.6549019608, alpha: 1)
    }) { (_) in
        sender.backgroundColor = .white
    }
}

答案 1 :(得分:0)

Robert Dresler的答案适用于选定但未突出显示的单元格。我要做的是创建UITableViewCell的子类,以这种方式将代码从其余逻辑中抽象出来,并创建可重用的代码。我将提供一个简单的示例;

class HighlightTableViewCell: UITableViewCell {

    var highlightColor: UIColor {
        didSet {
            highlightView.backgroundColor = highlightColor
        }
    }

    private var highlightView: UIView = UIView()

    override func awakeFromNib() {
        super.awakeFromNib()

        selectionStyle = .none

        addSubview(highlightView)
        highlightView.autoPinEdgesToSuperviewEdges()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        bringSubview(toFront: highlightView)
    }

    override func setHighlighted(_ highlighted: Bool, animated: Bool) {
        super.setHighlighted(highlighted, animated: animated)

        highlightView.isHidden = !highlighted
        highlightView.layoutIfNeeded()
    }
}
相关问题