ios - 用户输入中间的 UITextField 省略号,Swift
问题描述
是否可以在UITextField中间使用省略号?我找到的每个答案都是针对 UITextView 的。在我的应用程序中,我有文本字段,用户可以在其中粘贴他钱包的私钥,但它太长了,最后会被三个点切割,这是我想要实现的,因为在私钥中,最重要的字符是第一个很少和最后几个,有这样的东西:firstfewchar...lastfewchar
解决方案
受此答案的启发,您应该创建自己的自定义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()
}
}
当用户停止编辑文本字段时,将应用换行模式:
推荐阅读
- regex - 在 Hive 中使用正则表达式获取匹配数?
- excel - 粘贴范围返回变量范围的语法错误
- java - 合并排序和数组
- macos - Mac OS X 10.6 Swift 4.2 Xcode 10.0:此类与键的键值编码不兼容
- javascript - WKWebview evaluateJavaScript in swift 仅适用于某些网站
- android - 在 Android 的另一个程序中访问选定的文本
- c# - 带有图形的自动滚动面板
- javascript - “beforeunload”和“unload”事件如何工作?
- ios - Swift 4:无法让 NSPredicate 与 searchBar 和本地领域一起使用
- c# - 使用 lambda 表达式将日期时间转换为 MM yyyy、dd