如何在UITableViewCell上突出显示UIButton



如何在点击时设置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
}

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

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

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
}
}

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()
}
}

最新更新