繁体   English   中英

当用户在字段中键入至少一个字符时,uitextfield rightView可见

[英]uitextfield rightView visible when user typed at least one char in the field

我想知道是否有任何方法可以使UITextField的正确视图仅在内部至少有一个字符时才可见,因为通过设置UITextFieldViewModeWhileEditing将在我专注于字段时显示它,而不是在我开始输入时。

我只能想出实现UITextFieldDelegate并在用户输入时触发的其中一个方法上执行它。 这里唯一的问题是,在创建文本字段并将其添加到视图后,我将文本字段的委托更改为其他内容。 那是因为我通过UITextField创建了一个自定义文本字段,并在不同的地方初始化它,并在那些不同的地方我将它的委托分配给它发起的当前位置。

这是一个更好的主意。 UITextField发布更改通知。 您的子类可以通过这种方式观察自己:

// in RSSUITextField.m

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(textFieldChanged:)
                                             name:UITextFieldTextDidChangeNotification
                                           object:self];

然后实现textFieldChanged:并在那里更改rightView状态。 这个答案优于我剩下的那个,但我不会删除那个,因为它也有效,并且对于控件不发布关于我们关心的状态变化的通知的情况是一种有用的技术。

由于RSSUITextField的每个实例都将使用NSNotificationCenter进行观察,因此当它们不再重要时,每个实例都有责任将自己作为观察者移除。 最新的可能时间是dealloc ...

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

这个答案有效,但对于您的具体案例有更好的答案。 看到我的其他答案...文本字段在文本更改时发布NSNotification ....

KVO将是理想的,但UIKit不承诺KVO合规。 更抽象的问题陈述是,您希望一个对象知道文本字段的状态,该状态只能由委托知道,但有时您希望其他对象成为委托。

我唯一没有违反任何规则的想法是让子类成为真正委托的代理,就像这样......

// in RSSUITextField.m
@interface RSSUITextField () <UITextFieldDelegate>
// I will be my own delegate, but I need to respect the real one
@property (weak, nonatomic) id<UITextFieldDelegate>proxyDelegate;

@end

在指定的初始化...

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate = self;
    }
    return self;
}

我是我自己的委托,所以当这个类的调用者想要获取/设置委托时,我需要欺骗他......

- (id<UITextFieldDelegate>)delegate {
    return self.proxyDelegate;
}

- (void)setDelegate:(id<UITextFieldDelegate>)delegate {
    self.proxyDelegate = delegate;
}

现在重要的部分(然后悲伤的部分)。 重要的一部分:我们现在能够了解我们作为代表的州,并且仍然尊重来电者对代表的看法......

- (void)textFieldDidBeginEditing:(UITextField *)textField {

    // show or change my right view

    if ([self.proxyDelegate respondsToSelector:@selector(textFieldDidBeginEditing:)]) {
        [self.proxyDelegate textFieldDidBeginEditing:textField];
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {

    // hide or change my right view

    if ([self.proxyDelegate respondsToSelector:@selector(textFieldDidBeginEditing:)]) {
        [self.proxyDelegate textFieldDidBeginEditing:textField];
    }
}

可悲的是:我们打破了它,所以我们买了它。 为了完全尊重代表,我们必须传递所有代理消息。 这不是灾难,因为它们只有五个。 他们都将采取这种形式:

// I only added this one as an example, but do this with all five others
- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    if ([self.proxyDelegate respondsToSelector:@selector(textFieldShouldReturn:)]) {
        return [self.proxyDelegate textFieldShouldReturn:textField];
    } else {
        return YES;  // the default from the docs
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM