开发者

How to compare the instance of UITextField

开发者 https://www.devze.com 2023-01-08 14:58 出处:网络
I have 3 UIT开发者_开发技巧extFileds on a view, and I want to apply logic in UITextFieldDelegate method only in two of them, how do I determine the UITextField that triggered the call backs?

I have 3 UIT开发者_开发技巧extFileds on a view, and I want to apply logic in UITextFieldDelegate method only in two of them, how do I determine the UITextField that triggered the call backs?

Many thanks in Advance!


Usually, simple pointer comparison works, since you just want to check for object identity.

-(BOOL)textFieldShouldReturn:(UITextField*)textField {
   if (textField != theIgnoredTextField) {
      ...

Alternatively, you could assign .tags to the text field.

-(BOOL)textFieldShouldReturn:(UITextField*)textField {
   if (textField.tag != 37) {
      ...

The advantage is you don't need to store the reference to theIgnoredTextField, and the tag can be set from Interface Builder, but it relies on a recognizing magic number "37".


The delegate methods have a textfield parameter which is a point to the textfield object. You can compare that parameter to your textfield objects to see which one it is.

UITextField *field1, *field2, *field3;

In your delegate method you can compare the parameter:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range  replacementString:(NSString *)string
{
    if (textField == field1) {
        // do something special for field 1
    } ...


if you are using the delegate methods, such as - (void)textFieldDidEndEditing:(UITextField *)textField all you need to do is do something like

- (void)textFieldDidEndEditing:(UITextField *)textField
{
if (textField == myFirstTextField)
{
//blah
}
else if (textField == mySecondTextField)
{
//etc etc.
}
else
{
//WHEE!
}
}//method end


You can compare the pointers if you keep references to them in your class ivars or you can use UIView's tag property, whichever you like more.

0

精彩评论

暂无评论...
验证码 换一张
取 消