问题描述
当您在UITextField的某些文本下划线然后单击它时,如果光标位于带下划线的文本的右侧或内部,则整个文本字段都会带有下划线。有办法避免这种情况吗?
override func viewDidLoad() {
super.viewDidLoad()
let textField1 = UITextField(frame: CGRect(x: 20,y: 100,width: 300,height: 40))
textField1.borderStyle = UITextField.BorderStyle.roundedRect
textField1.allowsEditingTextAttributes = true
view.addSubview(textField1)
let textField2 = UITextField(frame: CGRect(x: 20,y: 150,height: 40))
textField2.borderStyle = UITextField.BorderStyle.roundedRect
textField2.allowsEditingTextAttributes = true
view.addSubview(textField2)
}
解决方法
这就是我的工作,结合了其他SO天才的解决方案。 请注意,视图控制器中的每个textView必须具有从0开始的唯一顺序标签。 如果有人有所改进,我将不胜感激。
var textViewPlaceholder1: UILabel!
var textViewPlaceholders = [UILabel]()
let kFontSize: CGFloat = 17.0
let kPlaceholderLeftInset: CGFloat = 8.0
override func viewDidLoad() {
super.viewDidLoad()
let textView1Frame = CGRect(x: 20.0,y: 100.0,width: 300.0,height: 34.0)
let textView1 = makeTextView(withFrame: textView1Frame)
textView1.tag = 0
// For testing: textView1.attributedText = NSAttributedString(string: "One two three",attributes: [.foregroundColor : UIColor.systemRed,.font : UIFont.systemFont(ofSize: kFontSize)])
view.addSubview(textView1)
let textViewPlaceholder1Frame = CGRect(x: textView1Frame.origin.x + kPlaceholderLeftInset,y: textView1Frame.origin.y,width: textView1Frame.width,height: textView1Frame.height)
textViewPlaceholder1 = UILabel(frame: textViewPlaceholder1Frame)
textViewPlaceholder1.attributedText = NSAttributedString(string: "Text view 1...",attributes: [.foregroundColor : UIColor.systemGray3,.font : UIFont.systemFont(ofSize: kFontSize)])
textViewPlaceholder1.isHidden = true
textViewPlaceholders.append(textViewPlaceholder1)
view.addSubview(textViewPlaceholder1)
let textField2 = UITextField(frame: CGRect(x: 20.0,y: 150.0,height: 34.0))
textField2.font = .systemFont(ofSize: kFontSize)
textField2.borderStyle = UITextField.BorderStyle.roundedRect
textField2.allowsEditingTextAttributes = true
textField2.placeholder = "Text field 2..."
view.addSubview(textField2)
}
func makeTextView(withFrame: CGRect) -> UITextView {
let textView = UITextView(frame: withFrame)
textView.delegate = self
textView.layer.cornerRadius = 5.0
textView.layer.borderWidth = 1.0
textView.layer.borderColor = UIColor.systemGray4.cgColor
textView.textContainerInset = UIEdgeInsets(top: 7.0,left: 2.0,bottom: 5.0,right: 5.0)
textView.font = .systemFont(ofSize: kFontSize)
textView.allowsEditingTextAttributes = true
return textView
}
func textView(_ textView: UITextView,shouldChangeTextIn range: NSRange,replacementText text: String) -> Bool {
guard text.rangeOfCharacter(from: CharacterSet.newlines) == nil else {
// textView.resignFirstResponder() // uncomment this to close the keyboard when return key is pressed
return false
}
if (range.location > 0 || text.count != 0) {
textViewPlaceholders[textView.tag].isHidden = true
} else {
textViewPlaceholders[textView.tag].isHidden = false
}
return true
}