UITextField 特别是只有一行。
使用UITextView 代替多行文本。
要在 UITextView 中实现占位符,请使用此逻辑/代码。
首先将 UITextView 设置为包含占位符文本并将其设置为浅灰色以模仿 UITextField 占位符文本的外观。在 viewDidLoad 中或在创建文本视图时这样做。
对于斯威夫特
textView.text = "Placeholder"
textView.textColor = UIColor.lightGrayColor()
对于 Objective-C
textView.text = @"Placeholder";
textView.textColor =[UIColor lightGrayColor];
然后当用户开始编辑文本视图时,如果文本视图包含占位符(即如果其文本颜色为浅灰色),则清除占位符文本并将文本颜色设置为黑色以适应用户的输入。
对于斯威夫特
func textViewDidBeginEditing(textView: UITextView) {
if textView.textColor == UIColor.lightGrayColor() {
textView.text = nil
textView.textColor = UIColor.blackColor()
}
}
对于 Objective-C
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
if (textView.textColor == [UIColor lightGrayColor]) {
textView.text = @"";
textView.textColor = [UIColor blackColor];
}
return YES;
}
然后,当用户完成对文本视图的编辑并辞去第一响应者的职务时,如果文本视图为空,则通过重新添加占位符文本并将其颜色设置为浅灰色来重置其占位符。
对于斯威夫特
func textViewDidEndEditing(textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Placeholder"
textView.textColor = UIColor.lightGrayColor()
}
}
对于 Objective-C
- (void)textViewDidEndEditing:(UITextView *)textView{
if ([textView.text isEqualToString:@""]) {
textView.text = @"Placeholder";
textView.textColor =[UIColor lightGrayColor];
}
}
还要在视图控制器中添加UITextViewDelegate。