2

我一直在寻找这个问题的答案,但我没有找到任何与我的具体问题相关的东西。我有多个 UILabel,我正在尝试根据按下的 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是存储标签文本的字符串。提前感谢您的帮助!

4

3 回答 3

2

你的方法应该奏效。某个细节有问题。我怀疑您忘记设置标签以接收触摸(默认情况下它们不会)。它应该像这样简单地工作......

// 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。他们在他们需要的地方;附加到子视图。(你总是可以通过说得到它们self.labelA.gestureRecognizers,但我在实践中很少发现需要)

- (void)tapped:(UIGestureRecognizer *)gr {

    UILabel *label = (UILabel *)gr.view;
    NSLog(@"the label tapped is %@", label.text);
}

注意这个方法的形式符合@abbood 的建议。第一个参数是 gr,可以通过这种方式访问​​,无需使用 ivar。这在我的 Xcode 中运行良好。

于 2013-07-28T14:26:40.513 回答
0

为什么不直接使用 UIButton 让它们看起来像标签?

UIButton whateverYouCallYourButton = [[UIButton alloc] init];
[whateverYouCallYourButton addTarget:self action:@selector(itemClicked:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:whateverYouCallYourButton];

然后像这样使itemClicked ...

- (void)itemClicked: (id)sender {
// stuff you want to do here
}
于 2013-07-28T13:11:02.717 回答
0

当您声明点击标签时调用的方法时(即 inputAnswer).. 它应该是这样的:

-(void)inputAnswer:(UITapGestureRecognizer *)gesture {
    strC = [answerFieldC text];
    // the gesture object tells you what you view you tapped
    currentLabel = gesture.view;

    if (currentLabel==answerFieldC) {
        [strC stringByAppendingString:[sender currentTitle]];
        [answerFieldC setText:strC];
    }
}
于 2013-07-28T13:59:33.240 回答