1

I have a XIB ProfileView contained within a custom UIViewController class Alarm. ProfileView has a subview UITextView, and I want to call UITextView delegate methods from my custom class Alarm instead of ProfileView because all of my logic concerning the text of the UITextView is in my Alarm class. So my question is: Can I call UITextView delegate methods from my Alarm class if the UITextView is a subview of ProfileView? In other words, can I set the UITextView delegate to Alarm instead of self?

enter image description here

Austin Berenyi
  • 1,013
  • 2
  • 13
  • 25
  • Are you saying you want *two* delegates for the UITextField? And what do you mean by "access delegate methods?" Delegate methods are called by the requesting object, not something you would "access" yourself. An object should have one-and-only-one delegate, so if you're wanting multiple objects to be informed of some change in the UITextField, then perhaps registering for notifications is more appropriate? Not sure what you're trying to accomplish, so perhaps you can add more context to your question. – christopherdrum May 16 '18 at 01:21
  • @christopherdrum thanks for adding clarity. I've edited my question. Hopefully it makes sense what I'm asking. I just want to call my `UITextView` delegate methods from `Alarm` instead of `ProfileView`. – Austin Berenyi May 16 '18 at 01:31
  • @AustinBerenyi Sorry but can I know why my answer can't be accepted as right answer? Your question has objective-c tag and you mark a Swift answer as right answer. One more, my answer is earlier answer. Be fair! – trungduc May 16 '18 at 02:34
  • @trungduc sorry for the mistake. Your answer should have been marked as the right answer first. Thank you for your help! – Austin Berenyi May 16 '18 at 02:46

2 Answers2

2
  • Connect and make UITextView as a public property of ProfileView

    @interface ProfileView : UIView
    @property (weak, nonatomic) IBOutlet UITextView *textView;
    @end
    
  • In your Alarm class, set self.profileView.textView.delegate = self and implement functions you need or if profileView isn't a property of Alarm, set delegate after you initialize it.

    @interface Alert : UIViewController <UITextViewDelegate>
    
    @property (nonatomic, strong) ProfileView* profileView;
    
    @end
    
    // In |viewDidLoad| or anywhere after you initialize |_profileView|
    self.profileView.textView.delegate = self;
    
trungduc
  • 11,926
  • 4
  • 31
  • 55
2

Yes you can.

By code in Alarm:

func viewDidLoad() {
    super.viewDidLoad()

    // If you have the UITextField @IBOutlet in your Alarm
    textField.delegate = self

    // If it's owned by ProfileView
    profileView.textField.delegate = self
}

Be sure Alarm is conformed to UITextFieldDelegate.


Or with Interface Builder, first drag from the UITextField to the Alarm object like this:

And then select delegate.

enter image description here

yesleon
  • 928
  • 11
  • 14