简体   繁体   中英

How to button highlight and highlight colour is red in swift

How to show button Highlight colour,,and the colour is red

extension LeaveDetailVC: cellIndexCall{
    func selectBtnIndex(sender: UIButton) {
        let buttonPosition:CGPoint = sender.convert(.zero, to:leaveDetailTableView)
        var indexPath = leaveDetailTableView.indexPathForRow(at: buttonPosition)
        self.indexPath = indexPath!
        print("\(String(describing: indexPath?.row))") /* index path of button
        self.menuClickIndex = (indexPath?.row)!   
    }
}

And my Button is cover the tableViewCell. And I also create a button delegate in cell class and call in viewController through extension.

I just want to highlight button and that is over cell.

  override func tableView(_ tableView: UITableView, shouldHighlightRowAt 
  indexPath: IndexPath) -> Bool {
    return true
   }

  override func tableView(_ tableView: UITableView, didHighlightRowAt 
  indexPath: 
   IndexPath) {
   let cell = tableView.cellForRow(at: indexPath)
   cell?.contentView.backgroundColor = UIColor.orange
   cell?.backgroundColor = UIColor.orange
 }

  override func tableView(_ tableView: UITableView, didUnhighlightRowAt 
  indexPath: IndexPath) {
     let cell = tableView.cellForRow(at: indexPath)
     cell?.contentView.backgroundColor = UIColor.black
     cell?.backgroundColor = UIColor.black
   }

In your viewController

class LeaveDetailVC: ViewController {
    var selectedRows: [IndexPath] = [] // i assume multiple select button

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCell(withIdentifier: "YOUR_CELL") as! YOUR_CELL_CLASS
          cell.isHighlight = selectedRows.indices.contains(indexPath) // Determine if cell was selected or not
    }
}

extension LeaveDetailVC: cellIndexCall {

    func selectBtnIndex(sender: UIButton) {
       let buttonPosition:CGPoint = sender.convert(.zero, to:leaveDetailTableView)
       var indexPath = leaveDetailTableView.indexPathForRow(at: buttonPosition)
       if selectedRows.indices.contains(indexPath) {
          if let index = selectedRows.index(of: indexPath) {
             self.selectedRows.remove(at: index) // remove selected indexpath
          }
       } else {
          self.selectedRows.append(indexPath) // add selected indexpath
       }
    }
}

In your cell class

var isHighlight: Bool = false

override func layoutSubviews() {
   super.layoutSubviews()

   // TODO : Set your button color based on isHighlight flag
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM