简体   繁体   中英

Custom Accessory Button in UITableViewCell

I am trying to add a custom button in the Accessory View for a UITableViewCell.

I have added the following code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {      
       // ....     
       let button = UIButton(type: .custom)
       button.setImage(UIImage(named: "arrow-right-light.png")?.maskWithColor(color: .white), for: .normal)
       button.addTarget(self, action: #selector(buttonTest), for: .touchUpInside)
       button.tag = indexPath.row
       cell.accessoryView = button
       // ...

However, I don't see the button show up on in the Accessory View.

I can think of two possible reasons:

  • The problem might be that the button has no size, so it's invisible. Add this line, after setting the image:

     button.sizeToFit()
  • Another possibility is that you have no image named "arrow-right-light.png" . That wouldn't crash your existing code, but it would prevent the button from having any image so you wouldn't see it. Try saying UIImage(named: "arrow-right-light.png")! instead, just as a test; if you crash, that was indeed the problem, and then you can figure out what the correct name is.

I tried @matt's solution above, but this makes the button as large as the image.

I showed a iOS builtin info image which is smaller than the minimum advised button size of 44x44 points . Although the button works, it's hard(er) to tap; which is a common invisible UX issue seen in many apps (even professional ones.

Therefore instead of calling button.sizeToFit() you must set the buttons height (I did my full cell height of 50) and width to a nice & easy tappable 60.

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