UITableViewCell 中的 UIButton 在模拟器中不工作 (iOS 14)
UIButton inside UITableViewCell not working in simulator (iOS 14)
更新 Xcode 到版本 12 后,添加到 UITableViewCell 的每个 UIButton 都像这样:
self.addSubview(someButton)
在模拟器(iOS 版本 14)中按钮不起作用(当用户点击按钮时没有任何反应)但在真实设备中一切正常。当我像这样将 UIButton 添加到单元格时,即使在模拟器中也一切正常:
self.contentView.addSubview(receptionButton)
为什么会这样?我通过这种方式 (self.contentView.addSubview) 向 UITableViewCell 添加 UIButton 是否正确?
and am I doing right by adding UIButton this way
(self.contentView.addSubview) to UITableViewCell?
是.
这是最正确的方法!您可以将子视图直接添加到 self
(单元格本身),就像在您的第一个代码块中一样,但是,您将来 100% 会遇到错误(我做到了),就像您现在刚刚经历的一样.
why this is happening?
这是我能从 Apple 找到的最好的解释:
The content view of a UITableViewCell object is the default superview for content that the cell displays. If you want to customize cells by simply adding additional views, you should add them to the content view so they position appropriately as the cell transitions in to and out of editing mode.
https://developer.apple.com/documentation/uikit/uitableviewcell/1623229-contentview
更新 Xcode 到版本 12 后,添加到 UITableViewCell 的每个 UIButton 都像这样:
self.addSubview(someButton)
在模拟器(iOS 版本 14)中按钮不起作用(当用户点击按钮时没有任何反应)但在真实设备中一切正常。当我像这样将 UIButton 添加到单元格时,即使在模拟器中也一切正常:
self.contentView.addSubview(receptionButton)
为什么会这样?我通过这种方式 (self.contentView.addSubview) 向 UITableViewCell 添加 UIButton 是否正确?
and am I doing right by adding UIButton this way (self.contentView.addSubview) to UITableViewCell?
是.
这是最正确的方法!您可以将子视图直接添加到 self
(单元格本身),就像在您的第一个代码块中一样,但是,您将来 100% 会遇到错误(我做到了),就像您现在刚刚经历的一样.
why this is happening?
这是我能从 Apple 找到的最好的解释:
The content view of a UITableViewCell object is the default superview for content that the cell displays. If you want to customize cells by simply adding additional views, you should add them to the content view so they position appropriately as the cell transitions in to and out of editing mode.
https://developer.apple.com/documentation/uikit/uitableviewcell/1623229-contentview