Detect Start and Stop Editing UITextView

后端 未结 4 1726
名媛妹妹
名媛妹妹 2021-02-06 22:39

How can I call some code upon entering a UITextView (user taps to edit it) and leaving the view (user taps to leave it)?

Appreciate any help.

4条回答
  •  醉话见心
    2021-02-06 23:26

    http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextViewDelegate_Protocol/Reference/UITextViewDelegate.html#//apple_ref/occ/intf/UITextViewDelegate

    Here you can find several useful methods to investigate:

    • textViewDidBeginEditing:
    • textViewDidEndEditing:

    Moreover to live UITextView you often should implement action that calls [yourTextView resignFirstResponder];

    Objective-C example

    //you may specify UITextViewDelegate protocol in .h file interface, but it's better not to expose it if not necessary
    @interface ExampleViewController() 
    
    @end
    
    @implementation ExampleViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        //assuming _textView is already instantiated and added to its superview
        _textView.delegate = self;
    }
    
    
    //it's nice to separate delegate methods with pragmas but it's up to your local code style policy
    #pragma mark UITextViewDelegate
    
    - (void)textViewDidBeginEditing:(UITextView *)textView {
        //handle user taps text view to type text
    }
    
    - (void)textViewDidEndEditing:(UITextView *)textView {
        //handle text editing finished    
    }
    
    @end
    

    Swift Example

    class TextViewEventsViewController: UIViewController, UITextViewDelegate {
    
        @IBOutlet weak var exampleTextView: UITextView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            self.exampleTextView.delegate = self
        }
    
        func textViewDidBeginEditing(_ textView: UITextView) {
            print("exampleTextView: BEGIN EDIT")
        }
    
        func textViewDidEndEditing(_ textView: UITextView) {
            print("exampleTextView: END EDIT")
        }
    }
    

提交回复
热议问题