点击文本字段时如何突出显示文本

How to highlight text when textfield is tapped

我希望在按下文本字段时突出显示文本字段中的文本,就像您在浏览器中按下网站文本时一样。我尝试 google 但找不到 swift/xcode 的直接答案。

感谢您的帮助:)

您的问题重复 this. The best answer there is to use delegate functions textFieldShouldBeginEditing and textFieldShouldEndEditing 以更改和恢复颜色。

为文本字段设置委托

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
    }
}

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({[=10=].layer.removeAllAnimations()})
        self.textField.layer.removeAllAnimations()
        self.textField.layoutIfNeeded()
    }
}

}

在您的 ViewController 中,您需要 link-up 将您的文本字段委托给自身。

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()
}

}

输出: