我可以通过长按来更新标签的价值 - iOS

时间:2014-04-24 08:26:34

标签: ios7 xcode5 uilabel long-press

我在iPhone iOS7设备上用Xcode 5编写了一个简单的应用程序。 我有一个增加+/-按钮的标签,但我想为用户提供选项,以便将他的号码插入此标签。 我怎么能用长按识别器做到这一点? 感谢。

1 个答案:

答案 0 :(得分:0)

使用UILongPressGestureRecognizerUITextView

向视图控制器添加UILongPressGstureRecognizer属性:

@property UILongPressGestureRecognizer *gestureRecognizer;

您需要声明视图控制器符合UITextViewDelegateUIGestureRecognizerDelegate协议:

@interface ViewController : UIViewController<UITextViewDelegate, UIGestureRecognizerDelegate>

viewDidLoad

self.textView.editable = NO;
self.textView.delegate = self;
self.gestureRecognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(textViewLongPressed:)];
self.gestureRecognizer.delegate = self;
[self.textView addGestureRecognizer:self.gr];

这是长按文本视图时将调用的方法:

-(void) textViewLongPressed:(UILongPressGestureRecognizer *)sender
{
    self.textView.editable = YES;
    [self.textView becomeFirstResponder];
}

UIGestureRecognizerDelegate

实施此方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    if (self.gestureRecognizer == gestureRecognizer){
        return YES;
    }
    return NO;
}

完成文本视图的编辑后

-(void) textViewDidEndEditing:(UITextView *)textView
{
    self.textView.editable = NO;
}

按返回时关闭键盘:

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
        [textView resignFirstResponder]; // or [textView endEditing:YES]

    return YES;
}