UIButton 在 UITableview 中不起作用
Posted
技术标签:
【中文标题】UIButton 在 UITableview 中不起作用【英文标题】:UIButton not working in UITableview 【发布时间】:2016-07-15 20:11:17 【问题描述】:Have UITableviewcell
--> 在其中我有 4 个不同的 UIView,其中 3 个视图有 UIButton。我想让UIButton
可点击。第一次按钮是可点击的,但是当我进入下一个屏幕并返回时,按钮不起作用。请让我知道如何实施?谢谢!
PHMyTripView *tripsView=[[PHMyTripView alloc] initWithFrame:CGRectMake(10, 5, self.frame.size.width-20, cell.frame.size.height)];
tripsView.onBaggageClick = ^
[weakSelf handleBaggagePurchaseTapped];
;
if ([data count]>0)
[tripsView fillTripData:[data firstObject]];
[tripsView showAncillaries:self.predictiveManager.upcomingCDAirBookingInfo];
[cell bringSubviewToFront:tripsView.bagsButton];
[cell.viewPlaceHolder addSubview:tripsView];
【问题讨论】:
显示整个代码 我已经更新了sn-p的代码。没有一个答案真的有帮助。我确实更改了按钮的背景颜色以查看它的框架一切都很好。但它只是不可点击,而是转到 didSelectRowAtIndexPath 方法。让我知道任何澄清。谢谢大家的回复。期待正确答案。 【参考方案1】:发生这种情况是因为单元格是可重复使用的,如果您转到另一个屏幕,按钮可能会在 UI 或功能上进入不同的单元格。
解决这个问题的方法是添加标签。可以定义 cell.tag = indexPath.row * 10 左右。
然后在绘制按钮时,检查条件,如果 cell.tag == ?,然后添加按钮。
【讨论】:
【参考方案2】:感谢大家的回复,但它们不适用于我的情况。 这是答案。由于 UITableview 在返回屏幕时正在重新加载。框架被错误放置,因此按钮无法单击。
使用了这一行代码,效果很好。
self.tripsView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
【讨论】:
【参考方案3】:您应该在每个UITableView
子视图上关闭delaysContentTouches
,这是UIScrollView
类的一个实例。
子类UITableView
并覆盖initWithFrame
方法:
.h 文件
@interface NoDelaysOnTouchTableView : UITableView
@end
还有.m文件
#import "NoDelaysOnTouchTableView.h"
@implementation NoDelaysOnTouchTableView
- (id) initWithFrame: (CGRect) frame
self = [super initWithFrame: frame];
if (self)
for (id view in self.subviews)
if ([NSStringFromClass([view class]) isEqualToString: @"UITableViewWrapperView"])
if ([view isKindOfClass: [UIScrollView class]])
// turn OFF delaysContentTouches in the hidden subview
UIScrollView* scroll = (UIScrollView*)view;
scroll.delaysContentTouches = NO;
break;
return self;
@end
下一步 - 使用这个子类(创建NoDelaysOnTouchTableView
的实例)能够立即按下UIButton
。
【讨论】:
【参考方案4】:我认为原因是多方面的。 你可以试试:
检查单元格中每个按钮的约束 在 cellForRow 中,您可以为每个具有相关 @selector 的按钮执行 addTarget:,并在此方法中检查与按钮关联的对象(数据源)。 不要在您的单元格中使用 addSubView,而是使用 Xib(或在 tableView 的情节提要中定义您的单元格),以便您可以设置约束。希望对你有所帮助。
【讨论】:
【参考方案5】:不是专门针对这个问题,但是对于某些人来说可能是这样。尝试在单元格的contentView
中添加子视图。
而不是addSubview(textField)
使用contentView.addSubview(textField)
【讨论】:
以上是关于UIButton 在 UITableview 中不起作用的主要内容,如果未能解决你的问题,请参考以下文章
如何将静态 UIButton 覆盖在 UITableView 上
如何将静态 UIButton 覆盖在 UITableView 上
为啥我的 UITableView 需要在场景大纲中的 UIButton 下面
如何管理 UITableView + 动态自定义单元格(UIBUtton + UITextField + UIBUtton)插入?