gpt4 book ai didi

swift - 具有不连续底部边框的自定义 UITextfield

转载 作者:行者123 更新时间:2023-11-28 07:27:11 25 4
gpt4 key购买 nike

Here is the result I want to achieve

我现在正在处理 UITextfield。我希望知道如何向 UITextfield 添加四个不连续的底部边框,以及如何使输入数字之间的间距更大,使它们分别恰好适合四行。此外,如果可能的话,当用户在该行输入数字时,如何使该行变为黑色(而其他行保持灰色)?非常感谢!

最佳答案

使用 UITextField 的以下子类,并在 Storyboard中或以编程方式为每个数字创建文本字段。

注意每个textfield都要设置一个标签,比如

第一个数字:textField1.tag=1

第二位数字:textField1.tag=2

第三位:textField1.tag=3

第 4 位:textField1.tag=4

class CustomTextField: UITextField {
private let normalStateColor = UIColor.lightGray.cgColor
private let focusStateColor = UIColor.black.cgColor

private let border = CALayer()
private let borderHeight: CGFloat = 4.0

// MARK:- Init
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
setup()
}

override init(frame:CGRect) {
super.init(frame:frame)
setup()
}

override func awakeFromNib() {
super.awakeFromNib()
setup()
}
// MARK:- Overrides
override func layoutSubviews() {
super.layoutSubviews()

let size = self.frame.size
self.border.frame = CGRect(x: 0, y: size.height - borderHeight, width: size.width, height: borderHeight)
}

override func willMove(toSuperview newSuperview: UIView!) {
guard newSuperview != nil else {
NotificationCenter.default.removeObserver(self)
return
}

NotificationCenter.default.addObserver(self, selector: #selector(beginEdit),
name: UITextField.textDidBeginEditingNotification, object: self)
NotificationCenter.default.addObserver(self, selector: #selector(endEdit),
name: UITextField.textDidEndEditingNotification, object: self)
}

@objc func beginEdit() {
border.backgroundColor = self.focusStateColor
}

@objc func endEdit() {
border.backgroundColor = self.normalStateColor
}

private func setup() {
border.backgroundColor = self.normalStateColor
textAlignment = .center
borderStyle = .none
layer.addSublayer(border)
delegate = self
}
}

extension CustomTextField: UITextFieldDelegate {

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.text!.count < 1 && string.count > 0 {
textField.text = string
textField.superview?.viewWithTag(textField.tag + 1)?.becomeFirstResponder()
return false
} else if textField.text!.count >= 1 && string.count == 0 {
textField.text = ""
textField.superview?.viewWithTag(textField.tag - 1)?.becomeFirstResponder()
return false
}

return true
}
}

那产量

enter image description here

关于swift - 具有不连续底部边框的自定义 UITextfield,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56231736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com