输入文本以点击UILabel?

时间:2013-07-28 12:32:15

标签: iphone ios objective-c uilabel uigesturerecognizer

我已经找到了这个问题的答案,但我没有找到任何与我的具体问题有关的内容。我有多个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是存储标签文本的字符串。在此先感谢您的帮助!

3 个答案:

答案 0 :(得分: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中运行良好。

答案 1 :(得分:0)

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

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

然后像这样makeClickClick ...

- (void)itemClicked: (id)sender {
// stuff you want to do here
}

答案 2 :(得分: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];
    }
}