gpt4 book ai didi

objective-c - 在 UILabel 上执行选择器会导致崩溃?

转载 作者:可可西里 更新时间:2023-11-01 05:06:46 24 4
gpt4 key购买 nike

我读到 UILabel 并不是为了响应触摸事件,我可以只使用 UIButton。但是,无论如何我都必须将 UILabel 子类化以覆盖另一个方法,所以我想我也可以使用标签来将对代码的更改保持在最低限度。

如何让我的标签响应触摸事件?显示的代码和错误如下。

UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(startingPoint, 5, 10, 22)];
tempLabel.text = equationText;
tempLabel.font = [UIFont systemFontOfSize:13];
[tempLabel sizeToFit];
[view addSubview:tempLabel];
[tempLabel addTarget:self action:@selector(updateLabel:) forControlEvents:UIControlEventTouchUpInside]; // UNRECOGNIZED SELECTOR SENT TO INSTANCE

最佳答案

由于 UILabel 不是控件,您不能发送 -addTarget:action:forControlEvents: 消息。您必须从您的应用程序中删除该行,因为您的标签不是控件并且永远不会响应该消息。相反,如果您想使用您的标签,您可以将其设置为交互式并向其添加手势识别器:

// label setup code omitted
UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(updateLabel:)];
[tempLabel setUserInteractionEnabled:YES];
[tempLabel addGestureRecognizer:tap];
[tap release]; // if not using ARC

手势识别器的回调将传递给触发它的手势识别器的实例,而不是像 Action 消息那样的控件。要获取触发事件的标签实例,请使用 -view 向传入的手势识别器发送消息。因此,如果您的 updateLabel: 方法可能实现如下:

- (void)updateLabel:(UIGestureRecognizer*)recognizer
{
// Only respond if we're in the ended state (similar to touchupinside)
if( [recognizer state] == UIGestureRecognizerStateEnded ) {
// the label that was tapped
UILabel* label = (UILabel*)[recognizer view];

// do things with your label
}
}

此外,手势识别器将调用具有多个状态的 Action 方法,类似于在 -touchesBegan:... 系列方法中找到的方法。您应该检查您是否仅在识别器处于适当状态时才提交工作。对于简单的点击手势识别器,您可能只想在识别器处于 UIGestureRecognizerStateEnded 状态时工作(参见上面的示例)。有关手势识别器的更多信息,请参阅 UIGestureRecognizer 的文档.

关于objective-c - 在 UILabel 上执行选择器会导致崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9058615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com