Richa Netto
Richa Netto

Reputation: 315

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.

Upvotes: 5

Views: 5614

Answers (2)

meaning-matters
meaning-matters

Reputation: 22946

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.

Upvotes: 0

matt
matt

Reputation: 534925

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.

Upvotes: 9

Related Questions