如何在输入UITextView(用户点按以编辑它)并离开视图(用户点击以离开它)时调用某些代码?
感谢任何帮助。
答案 0 :(得分:40)
您可以在这里找到几种有用的方法进行调查:
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")
}
}
答案 1 :(得分:6)
您还可以实现 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 :(得分:2)
使用委托并使用:
- (void) textViewDidBeginEditing:(UITextView *) textView {
// Your code here
}
答案 3 :(得分:0)
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;
};