是否可以在UITextField中间使用省略号?我找到的每个答案都是针对 UITextView 的。在我的应用程序中,我有文本字段,用户可以在其中粘贴他钱包的私钥,但它太长了,最后会被三个点切割,这是我想要实现的,因为在私钥中,最重要的字符是第一个很少和最后几个,有这样的东西:firstfewchar...lastfewchar
问问题
148 次
2 回答
0
受此答案的启发,您应该创建自己的自定义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()
}
}
当用户停止编辑文本字段时,将应用换行模式:
于 2021-08-31T07:21:21.920 回答
0
我认为您可以通过执行以下步骤来实现
- 将委托方法设置为您的文本字段。
- 创建一个新的字符串属性来存储用户粘贴的原始值。
- 定义您自己的文本剪切规则,并在用户停止编辑时将文本字段的当前文本替换为剪切文本。
- 当用户开始编辑时,将剪切的文本替换为原始文本。
于 2021-08-31T07:10:32.053 回答