首页 > 解决方案 > 用户输入中间的 UITextField 省略号,Swift

问题描述

是否可以在UITextField中间使用省略号?我找到的每个答案都是针对 UITextView 的。在我的应用程序中,我有文本字段,用户可以在其中粘贴他钱包的私钥,但它太长了,最后会被三个点切割,这是我想要实现的,因为在私钥中,最重要的字符是第一个很少和最后几个,有这样的东西:firstfewchar...lastfewchar

标签: iosswiftuitextfieldellipsis

解决方案


受此答案的启发,您应该创建自己的自定义UITextField子类,并将文本字段的属性文本的换行模式设置为.byTruncatingMiddle

class MyTextField: UITextField {
    override var text: String? {
        didSet {
            makeTextTruncateInMiddle()
        }
    }
    
    private func makeTextTruncateInMiddle() {
        guard let newAttributedText = (attributedText?.mutableCopy() as? NSMutableAttributedString) else {
            return
        }
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineBreakMode = .byTruncatingMiddle
        newAttributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedText?.length ?? 0))
        attributedText = newAttributedText
    }
    
    override func resignFirstResponder() -> Bool {
        makeTextTruncateInMiddle()
        return super.resignFirstResponder()
    }
}

当用户停止编辑文本字段时,将应用换行模式:

在此处输入图像描述


推荐阅读