iphone - 输入文本到点击的 UILabel?

标签 iphone ios objective-c uilabel uigesturerecognizer

我一直在寻找这个问题的答案,但我没有找到任何与我的具体问题相关的内容。我有多个 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/

相关文章:

ios - 为什么在 Objective-C 的函数定义中使用 (__weak Class)?

objective-c - 如何删除我在 iphone sdk 中绘制到图像上的上下文?

ios - UIWebview 的 subview 没有响应加载请求

iphone - 发现多个名为 'tag' 的方法结果不匹配

iPhone 应用程序因 sqlite3_bind_text() 而崩溃

ios - 在 Facebook 墙上发布字符串而不显示对话框(iPhone Facebook SDK)

ios - 未找到有效的签名身份 - 适用于一台机器,不适用于另一台机器

ios - 如何区分在 iOS 上单击的音量按钮与软件设置的音量按钮

iphone - 为什么 viewDidAppear/viewWillAppear 不会在嵌套结构中被调用?

ios - 如何避免 MKMapView 刷新?