简体   繁体   English

UITableViewCell 中的自定义附件按钮

[英]Custom Accessory Button in UITableViewCell

I am trying to add a custom button in the Accessory View for a UITableViewCell.我正在尝试在 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" .另一种可能性是您没有名为"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")!试着说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.我尝试了上面@matt 的解决方案,但这会使按钮与图像一样大。

I showed a iOS builtin info image which is smaller than the minimum advised button size of 44x44 points .我展示了一个 iOS 内置信息图像,它小于44x44 点最小建议按钮大小 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.因此,不是调用button.sizeToFit()您必须将按钮高度(我将整个单元格高度设为 50)和宽度设置为一个漂亮且易于点击的 60。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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