textFieldShouldReturn not being called in iOS

2020-05-21 08:25发布

We're trying to figure out how to get the keyboard to hide, but we're having problems getting the textFieldShouldReturn to fire. Why?

This is what has been done:

*.h

@interface MultiSalesViewController : UIViewController <UITextFieldDelegate>

*.c

txtCardNumber.delegate = self;

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField setUserInteractionEnabled:YES];
    [textField resignFirstResponder];
    return YES;
}

Also, the textField has its delegate set to Files Owner in Interface Builder. One odd thing, is that the viewController's - (void)textFieldDidEndEditing:(UITextField *)textField is working.

How to get the hiding of the keyboard working?

10条回答
太酷不给撩
2楼-- · 2020-05-21 08:52

I see you put it in your code, but for future visitors, add this to your code:

yourTextField.delegate = self;

查看更多
爷的心禁止访问
3楼-- · 2020-05-21 08:52

following is answer from Mike Gledhill and Warren Crowther updated with xcode 5 screenshot.

(to set UITextField delegate, press and hold ctrl + drag from the UITextField to the "File's Owner" yellow button, shown in image below. if UITextField delegate not set, textFieldShouldReturn method never gets called).

enter image description here

查看更多
贼婆χ
4楼-- · 2020-05-21 09:00

I think you are using xib. If so You also need to set delegate over there. Do Right Click on your UITextfiled in xib and you will have delegate option drag it to your file owner.

查看更多
劫难
5楼-- · 2020-05-21 09:04

I had the delegate set and everything. But I was using a UITextView instead of UITextfield...

Perhaps this will help someone trying to figure why delegate methods are not fired.

查看更多
登录 后发表回答