UITextField:前导截断

UITextField: Leading Truncate

目前,我在 UITextField 中的文本在尾部被截断(例如“Hello, Wor...”)。我想要从前沿截断文本(例如“...lo,World!”)。

我相信将 NSMutableParagraphStyle's lineBreakModeNSMutableAttributedString 一起使用可能会奏效

let longString = "Hello World"

// Just for demo purposes, you can use auto layout etc
let textfield = UITextField(frame: CGRect(x: 40, y: 200, width: 30, height: 100))
textfield.layer.borderWidth = 2
textfield.layer.borderColor = UIColor.gray.cgColor

// Use a paragraph style to define the truncation method
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingHead

// Create an attributed string and apply the paragraph style
let attributedString = NSMutableAttributedString(string: longString)
attributedString.addAttribute(.paragraphStyle,
                              value: paragraphStyle,
                              range:NSMakeRange(0, attributedString.length))

// Set the text field's attributed text as the attributed string
textfield.attributedText = attributedString

这给出了这样的东西,这就是我认为你想要的:

您只需更新文本属性(例如,defaultTextAttributes) with a .paragraphStyle with a lineBreakMode of .byTruncatingHead

不过,我不会只替换 .paragraphStyle。我会获取它,更新它的 lineBreakMode,然后用它更新文本属性:

let oldStyle = textField.defaultTextAttributes[.paragraphStyle, default: NSParagraphStyle()] as! NSParagraphStyle
let style = oldStyle.mutableCopy() as! NSMutableParagraphStyle
style.lineBreakMode = .byTruncatingHead
textField.defaultTextAttributes[.paragraphStyle] = style

这里分别是.byTruncatingHead.byTruncatingMiddle.byTruncatingTail