我一直在寻找这个问题的答案,但我没有找到任何与我的具体问题相关的内容。我有多个 UILabels,并且我试图根据按下的 UIButton 来更改文本(类似于 iphone 上的电话功能)。我有这个方法适用于单个已知的 UILabel。但是,我现在尝试在存在多个标签时写入标签。我想通过点击标签来识别要向哪个标签写入文本,但我无法使代码正常工作...我的方法如下:
// init method
answerFieldC.userInteractionEnabled = YES;
touch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(inputAnswer:)];
[touch setNumberOfTapsRequired:1];
[answerFieldC addGestureRecognizer:touch];
-(IBAction)inputAnswer:(id)sender {
strC = [answerFieldC text];
currentLabel = touch.view;
if (currentLabel==answerFieldC) {
[strC stringByAppendingString:[sender currentTitle]];
[answerFieldC setText:strC];
}
}
其他标签在相同的 inputAnswer 和 init 代码下运行。 answerFieldC
是标签,strC
是存储标签文本的字符串。预先感谢您的帮助!
最佳答案
你的方法应该有效。有一个细节出了问题。我怀疑您忘记设置标签来接收触摸(默认情况下不会)。它应该像这样简单地工作......
// MyViewController.m
@property(weak, nonatomic) IBOutlet UILabel *labelA; // presumably these are painted in IB
@property(weak, nonatomic) IBOutlet UILabel *labelB;
// notice no gesture recognizer ivars here
// @implementation ...
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *tapA = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
[self.labelA addGestureRecognizer:tapA];
// You can set this in IB, but it must be set somewhere
self.labelA.userInteractionEnabled = YES;
UITapGestureRecognizer *tapB = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
[self.labelB addGestureRecognizer:tapB];
self.labelB.userInteractionEnabled = YES;
}
请注意两件事:(1) 我们在标签上设置 userInteractionEnabled = YES,(2) 有两个手势识别器,一个为每个标签执行一项工作。我们不需要为他们提供 ivars。他们就在他们需要在的地方;附加到 subview 。 (你总是可以通过说self.labelA.gestureRecognizers
来获得它们,但我在实践中很少发现需要这样做)
- (void)tapped:(UIGestureRecognizer *)gr {
UILabel *label = (UILabel *)gr.view;
NSLog(@"the label tapped is %@", label.text);
}
请注意,此方法的形式符合@abbood 的建议。第一个参数是 gr,可以通过这种方式访问,而无需使用 ivar。这在我的 Xcode 中运行良好。
关于iphone - 输入文本到点击的 UILabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17908227/