我需要向用户显示一个多行文本输入“框”,其高度大于UITextField
的标准高度。什么是最好的或最正确的方法?
UITextField
并在代码中更改其高度或应用特定的高度约束。UITextView
。这是多行的,但默认情况下它没有占位符,我想我应该在代码中实现这个特性。发布于 2016-09-01 11:45:11
UITextField
是专门的一行。
对多行文本使用UITextView
代替。
要在UITextView中实现占位符,请使用此逻辑/代码。
首先,将UITextView设置为包含占位符文本,并将其设置为浅灰颜色,以模仿UITextField的占位符文本的外观。要么在viewDidLoad
中这样做,要么在文本视图的创建上这样做。
For Swift
textView.text = "Placeholder"
textView.textColor = UIColor.lightGrayColor()
For Objective C
textView.text = @"Placeholder";
textView.textColor =[UIColor lightGrayColor];
然后,当用户开始编辑文本视图时,如果文本视图包含占位符(如果其文本颜色为淡灰色),则清除占位符文本,并将文本颜色设置为黑色,以适应用户的输入。
For Swift
func textViewDidBeginEditing(textView: UITextView) {
if textView.textColor == UIColor.lightGrayColor() {
textView.text = nil
textView.textColor = UIColor.blackColor()
}
}
For Objective C
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
if (textView.textColor == [UIColor lightGrayColor]) {
textView.text = @"";
textView.textColor = [UIColor blackColor];
}
return YES;
}
然后,当用户完成编辑文本视图,并将其作为第一个响应者时,如果文本视图为空,则通过重新添加占位符文本并将其颜色设置为淡灰色来重置其占位符。
For Swift
func textViewDidEndEditing(textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Placeholder"
textView.textColor = UIColor.lightGrayColor()
}
}
For Objective C
- (void)textViewDidEndEditing:(UITextView *)textView{
if ([textView.text isEqualToString:@""]) {
textView.text = @"Placeholder";
textView.textColor =[UIColor lightGrayColor];
}
}
也要在视图控制器中添加UITextViewDelegate
。
发布于 2016-09-01 11:58:47
选择二,textField的高度不能改变,它不显示第二行.
占位符逻辑:
textView.text = "Placeholder"
textView.textColor = UIColor.lightGrayColor()
func textViewDidBeginEditing(textView: UITextView) {
if textView.textColor == UIColor.lightGrayColor() {
textView.text = nil
textView.textColor = UIColor.blackColor()
}
}
func textViewDidEndEditing(textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Placeholder"
textView.textColor = UIColor.lightGrayColor()
}
}
发布于 2017-06-29 16:53:46
Swift 3 3
UITextView
本身没有占位符属性,因此您必须使用UITextViewDelegate
方法以编程方式创建和操作占位符属性。
(注意:将UITextViewDelegate
添加到类中并设置textView.delegate = self
。)
首先,将UITextView
设置为包含占位符文本,并将其设置为淡灰色,以模仿UITextField
占位符文本的外观。要么在viewDidLoad
中这样做,要么在文本视图的创建上这样做。
textView.text = "Placeholder"
textView.textColor = UIColor.lightGray
然后,当用户开始编辑文本视图时,如果文本视图包含占位符(如果其文本颜色为淡灰色),则清除占位符文本,并将文本颜色设置为黑色,以适应用户的输入。
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.textColor == UIColor.lightGray {
textView.text = nil
textView.textColor = UIColor.black
}
}
然后,当用户完成编辑文本视图,并将其作为第一个响应者时,如果文本视图为空,则通过重新添加占位符文本并将其颜色设置为淡灰色来重置其占位符。
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Placeholder"
textView.textColor = UIColor.lightGray
}
}
https://stackoverflow.com/questions/39270123
复制相似问题