Определить запуск и остановку редактирования UITextView - PullRequest
34 голосов
/ 09 ноября 2010

Как я могу вызвать некоторый код после входа в UITextView (пользователь нажимает, чтобы отредактировать его) и выхода из представления (пользователь нажимает, чтобы покинуть его)?

Ценить любую помощь.

Ответы [ 4 ]

40 голосов
/ 09 ноября 2010

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

Здесь вы можете найти несколько полезных методов исследования:

  • textViewDidBeginEditing:
  • textViewDidEndEditing:

Более того, чтобы жить UITextView вам часто следует реализовывать действие, которое вызывает [yourTextView resignFirstResponder];

Пример Objective-C

//you may specify UITextViewDelegate protocol in .h file interface, but it's better not to expose it if not necessary
@interface ExampleViewController()<UITextViewDelegate> 

@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 Пример

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")
    }
}
6 голосов
/ 11 июня 2015

Также можно реализовать методы делегата UITextViewDidChange .Я использую приведенный ниже код в своем приложении для быстрых заметок.Всякий раз, когда пользователь вводит символ, наблюдатель ловит его из центра уведомлений и вызывает метод saveText .

Вот как:

Добавьте эту строку в viewDidLoad метод:

[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:nil];

и эти строки в соответствующем месте в вашем коде (как в разделе, который обрабатывает методы делегата текстового представления. СОВЕТ: Используйте для этого прагма ()#pragma mark - Методы делегирования TextView ):

- (void)textViewDidChange:(UITextView *)textView{

    NSLog(@"textViewShouldEndEditing"); // Detect in log output if the method gets called
    [self saveText:nil]; // Call any method you like

}
2 голосов
/ 10 июня 2015

используйте делегата и используйте:

- (void) textViewDidBeginEditing:(UITextView *) textView {
    // Your code here
}
0 голосов
/ 15 марта 2019
txtviewaddress.text="Address"

txtViewAddress.TextColor = UIColor.LightGray;
txtViewAddress.ShouldBeginEditing += (textView) =>
        {
 txtViewAddress.Text = "";
            txtViewAddress.TextColor = UIColor.Black;
            return true;
};
txtViewAddress.ShouldEndEditing += (textView) =>
        {
            if (textView.Text == "")
            {
                txtViewAddress.Text = " Address";
                txtViewAddress.TextColor = UIColor.LightGray;

            }
            return true;
        };
...