【问题标题】:Wierd issues when performing selector "selectAll" on UITextField在 UITextField 上执行选择器“selectAll”时出现奇怪的问题
【发布时间】:2014-09-02 18:31:04
【问题描述】:

我面临着有史以来最奇怪的错误(我的应用程序或 IOS 7.1 中的以太币)。 几个小时后,我设法创建了一个简单的应用程序来演示这个问题。

两个 UITextField - 从界面生成器拖放并连接到 t1、t2。 视图控制器:

@implementation ViewController
@synthesize t1;
@synthesize t2;
#pragma mark - UITextFieldDelegate


-(void)textFieldDidBeginEditing:(UITextField *)iTextField {
    NSLog(@"textFieldDidBeginEditing");
    [iTextField performSelector:@selector(selectAll:) withObject:iTextField afterDelay:0.0];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    t1.delegate = self;
    t2.delegate = self;
}

@end

同时点击 t1 和 t2 时,两个 textField 都会成为无限循环中的第一响应者! 当省略执行选择器语句或 textField:shouldChangeCharactersInRange: 实现时,问题就消失了。

谁能解释为什么会这样?

【问题讨论】:

  • 试试[iTextField selectAll:self];怎么样?
  • 它导致问题消失但又产生了另一个问题。如果 textField 包含文本,点击 textField 选择所有文本。关闭键盘并再次点击时,文本不会再次被选中。

标签: ios objective-c uitextfield selectall


【解决方案1】:

我尝试使用selectedTextRange 属性来代替selectAll,这样就解决了无限循环的问题。

func textFieldDidBeginEditing(_ textField: UITextField) {
    DispatchQueue.main.async {
        let begin = textField.beginningOfDocument
        let end = textField.endOfDocument
        textField.selectedTextRange = textField.textRange(from: begin, to: end)
    }
}

【讨论】:

    【解决方案2】:

    编辑:还将每个UITextField的exclusiveTouch属性设置为:YES,以防止它们同时编辑。

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        t1.exclusiveTouch = YES;
        t2.exclusiveTouch = YES;
        t1.delegate = self;
        t2.delegate = self;
    }
    
    - (void)textFieldDidBeginEditing:(UITextField *)iTextField
    {
        [iTextField performSelector:@selector(selectAll:) withObject:nil afterDelay:0.0];
    }
    

    或者更简单地说,不使用 ExclusiveTouch 属性:

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)iTextField
    {
        if (iTextField == t1 && t2.isFirstResponder == NO)
        {
            return YES;
        }
        else if (iTextField == t2 && t1.isFirstResponder == NO)
        {
            return YES;
        }
    
        return NO;
    }
    

    【讨论】:

    • 没有帮助。注意 iTextField 携带 sender。
    • 哪一部分对你有用?设置独占触摸,还是使用 - (BOOL)textFieldShouldBeginEditing 方法?
    • 具有exclusiveTouch 的那个影响了我的scrollView 中的缩放操作(textField 是scrollview 的子视图)。第二种方法对我有用。
    • 很高兴听到@Yony
    猜你喜欢
    • 2010-11-02
    • 2012-11-22
    • 1970-01-01
    • 2012-03-11
    • 2017-10-22
    • 2011-04-02
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多