【发布时间】:2021-08-10 10:20:11
【问题描述】:
我希望在按下文本字段时突出显示文本字段中的文本,就像在浏览器中按下网站文本一样。我试图用谷歌搜索,但找不到 swift/xcode 的直接答案。
感谢您的帮助:)
【问题讨论】:
-
突出显示或选择?如果未选中,则检查
NSAttributedString,否则检查selectionRange?
我希望在按下文本字段时突出显示文本字段中的文本,就像在浏览器中按下网站文本一样。我试图用谷歌搜索,但找不到 swift/xcode 的直接答案。
感谢您的帮助:)
【问题讨论】:
NSAttributedString,否则检查selectionRange?
您的问题与this 重复。最好的答案是使用委托函数 textFieldShouldBeginEditing 和 textFieldShouldEndEditing 来更改和恢复颜色。
【讨论】:
textFieldDidBeginEditing
这不会实现你真正想要的,因为根据 UITextField 生命周期,这个方法将在编辑开始和即将结束时触发。您需要的是,通过点击文本字段突出显示确切的时刻。
首先将您的突出显示和正常状态外观分开。
extension MainView {
func textFieldActiveDisplay() {
self.isTextFieldOpen = true
let color = COLOR
let animation: CABasicAnimation = CABasicAnimation(keyPath: "borderColor")
animation.fromValue = textField.layer.borderColor
animation.toValue = color
animation.duration = 0.3
textField.layer.borderColor = color.cgColor
let borderWidth: CABasicAnimation = CABasicAnimation(keyPath: "borderWidth")
borderWidth.fromValue = 0
borderWidth.toValue = 4
borderWidth.duration = 0.2
searchBar.layer.borderWidth = 4
let group = CAAnimationGroup()
group.animations = [animation, borderWidth]
searchBar.layer.add(group, forKey: nil)
textField.font = HIGHLIGHTED_FONT
textField.textColor = HIGHLIGHTED_COLOR
}
func textFieldInActiveDisplay() {
guard isTextFieldOpen else { return }
let borderWidth: CABasicAnimation = CABasicAnimation(keyPath: "borderWidth")
borderWidth.fromValue = 4
borderWidth.toValue = 0
borderWidth.duration = 0.2
textField.layer.borderWidth = 0
textField.layer.add(borderWidth, forKey: nil)
textField.font = NORMAL_FONT
textField.textColor = NORMAL_COLOR
self.isTextFieldOpen = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.textField.subviews.forEach({$0.layer.removeAllAnimations()})
self.textField.layer.removeAllAnimations()
self.textField.layoutIfNeeded()
}
}
}
在您的 ViewController 中,您需要将文本字段的委托链接到自身。
override func viewDidLoad() {
super.viewDidLoad()
view.textField.delegate = self
}
extension MainViewController: UITextFieldDelegate, UIGestureRecognizerDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
view.textFieldActiveDisplay()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
view.textFieldInActiveDisplay()
}
}
【讨论】:
为文本字段设置委托
TF.delegate = self
在委托中添加代码
extension viewcontroller: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.layer.borderWidth = 2
textField.layer.borderColor = global().defaultColor().cgColor
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.layer.borderWidth = 0
}
}
【讨论】: