簡體   English   中英

如何在UITableViewCell上突出顯示UIButton

[英]How to highlight UIButton over UITableViewCell

如何在單擊時設置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()
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM