UITextField with Multiple Delegates

I am trying to create a text box that can answer the following:

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField

For this, I have a subclass of UITextField, which is a delegate for myself:

[self setDelegate:self]
  • Problem No. 1: on an ios5 device, the application crashes as soon as you click on a text field that has a set of self delegates
  • Problem No. 2: I still need text fields to send delegate notifications to other objects.

QUESTION: What would be the easiest way to implement delegate methods in a subclass, but still allow another object to be a delegate and receive the same messages?

thanks

+4
source share
3

( Swift 3). delegate UITextField.

:

class CustomTextField: UITextField, UITextFieldDelegate {

    override public init(frame: CGRect) {
        super.init(frame: frame)
        initCustomTextField()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initCustomTextField()
    }

    private func initCustomTextField() {
        super.delegate = self // Note the super qualifier.
    }

    ...

delegate:

private weak var userDelegate: UITextFieldDelegate?

override var delegate: UITextFieldDelegate? {
    get { return userDelegate }
    set { userDelegate = newValue }
}

, UITextFieldDelegate , :

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    // Do your thing here, and then forward:
    return self.delegate?.textFieldShouldBeginEditing?(self) ?? true
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    // Do your thing here, and then forward:
    self.delegate?.textFieldDidEndEditing?(self)
}

...

, iOS 10:

func textFieldDidEndEditing(_ textField: UITextField) {
    self.delegate?.textFieldDidEndEditing?(self)
}

/// This method will be called, instead of the above, on iOS ≥ 10.
@available(iOS 10.0, *)
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
    self.delegate?.textFieldDidEndEditing?(self, reason: reason)
}
+6

Notifications. , :

[[NSNotificationCenter defaultCenter] postNotificationName:@"custom notification name" object:self];

, :

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cacheUpdated:) name:@"custom notification name" object:nil];

, , , , , . , .

0

To create your own delegate you need to define a new protocol in your subclass

@protocol MyUItestFieldDelegate <NSObject>

- (void)customUITextFieldDelegateMethod;

@end

which you can use in your controller, for example

@interface MyViewController : UIViewController <MyUItestFieldDelegate>
0
source

Source: https://habr.com/ru/post/1523319/


All Articles