我的UITableView中只有一个单元格,我在单元格中添加了一个UIButton。 在touchUpInside事件发生时设置操作。但它根本不起作用。同时,如果 我将触发器设置为touchDown事件而不是touchUpInside,它将触发我设置的动作。
我通过谷歌搜索原因,有人说这个问题可能是由superview的维度引起的。这就是按钮的大小超出了它的超级视图。 所以我添加一个UIView来包含按钮,代码如下:
self.ageDisplay = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
UIImage *ageImage = [UIImage imageNamed:@"long_btn_click.png"];
[self.ageDisplay setImage:ageImage forState:UIControlStateSelected];
[self.ageDisplay setFrame:CGRectMake(10, 5, 145, 34)];//(10, 320, 145, 25)];
[self.ageDisplay setTitle:@"请选择您的年龄" forState:UIControlStateNormal];
[self.ageDisplay setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.ageDisplay setTag:3];
[self.ageDisplay addTarget:self action:@selector(showSelectionPage:) forControlEvents:UIControlEventTouchDown];
self.buttonsSubView = [[UIView alloc] initWithFrame:CGRectMake(0, 310, 320, 106)];
//self.buttonsSubView.backgroundColor = [UIColor blueColor];
[self.buttonsSubView setUserInteractionEnabled:YES];
[self.buttonsSubView addSubview:self.ageDisplay];
上面的代码在ViewDidLoad函数中。
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *sugPageCell = @"SuggestionPageCell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:sugPageCell];
if (nil == cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sugPageCell];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[cell addSubview:self.sugTitle];
[cell addSubview:self.sugSpecification];
[cell addSubview:self.suggestion];
self.buttonsSubView.userInteractionEnabled = YES;
[cell addSubview:self.buttonsSubView];
/*
[cell addSubview:self.ageDisplay];
[cell addSubview:self.genderDisplay];
[cell addSubview:self.submit];
*/
return cell;
}
但是,这没有用。 这个问题困扰了我2天。 如果有人能提供一些指示,我将不胜感激。 谢谢。
答案 0 :(得分:4)
这是因为你的buttonSubView视图在单元格的框架之外。 因此,即使按钮可见(因为单元格的clipsToBounds设置为NO),它也不会从单元格接收触摸事件。为什么要将此视图的垂直位置设置为310?
如果您尝试这样做:
self.buttonsSubView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 106)];
该事件应该随心所欲。
答案 1 :(得分:1)
我最近遇到了这个问题。我想可能会有一个UITapGesture
的对象添加到您的UITableView
。如果是,请将cancelsTouchesInView
对象的属性UITapGesture
设置为NO。
例如:
UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:target action:tapAction];
gesture.cancelsTouchesInView = NO;
[self addGestureRecognizer:gesture];