iOS Swift -如何为UITextView添加不可编辑的后缀

nbysray5  于 2023-06-21  发布在  Swift
关注(0)|答案(2)|浏览(99)

如何以编程方式向UITextView添加后缀(“kr”)?

谢谢

wgmfuz8q

wgmfuz8q1#

我假设这是当用户键入以指示货币值时。
在viewDidLoad中,指定您的textview委托(或您希望指定委托的任何位置):

override func viewDidLoad() {
    super.viewDidLoad()
    myTextView.delegate = self
}

,然后在用户键入时向textview添加后缀

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

    if string.characters.count > 0 {
        amountTypedString += string
        let newString = amountTypedString + "kr"
        myTextView.text = newString
    } else {
        amountTypedString = String(amountTypedString.characters.dropLast())
        if amountTypedString.characters.count > 0 {
            let newString = amountTypedString + "kr"
            myTextView.text = newString
        } else {
            myTextView.text = "0kr"
        }
    }
    return false
}
cs7cruho

cs7cruho2#

另一个可能对某些人有所帮助的解决方案是扩展UITextField并添加一个位于视图中心的幻影标签,该幻影标签应该使用UITextField中的相同文本值进行更新,并具有相同的字体大小。之后,将后缀约束到虚拟标签的尾部约束。

class TextWithSuffix: UITextField, UITextFieldDelegate {

private lazy var textPhantom = {
    let label = UILabel()
    label.font = UIFont.boldSystemFont(ofSize: 26)
    label.textColor = .clear
    return label
}()

private lazy var suffix = {
    let label = UILabel()
    label.text = "kr"
    label.font = UIFont.boldSystemFont(ofSize: 20)
    label.textColor = .white.withAlphaComponent(0.7)
    return label
}()

override init(frame: CGRect) {
    super.init(frame: frame)
    delegate = self
    textAlignment = .center
    font = UIFont.boldSystemFont(ofSize: 26)
    textColor = .white

    addConstrainedSubviews(textPhantom, suffix)
    NSLayoutConstraint.activate([
        textPhantom.centerXAnchor.constraint(equalTo: centerXAnchor),
        textPhantom.centerYAnchor.constraint(equalTo: centerYAnchor),

        suffix.leadingAnchor.constraint(equalTo: textPhantom.trailingAnchor, constant: 2),
        suffix.centerYAnchor.constraint(equalTo: textPhantom.centerYAnchor)
    ])
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func textField(
    _ textField: UITextField,
    shouldChangeCharactersIn range: NSRange,
    replacementString string: String
) -> Bool {
    let currentString = (textField.text ?? "") as NSString
    let newString = currentString.replacingCharacters(in: range, with: string)[enter image description here][1]
    textPhantom.text = newString
    return true
}

}

相关问题