UITextField: Leading Truncate

Viewed 277

Currently, my text within a UITextField is truncating at the tail (eg. "Hello, Wor..."). I want the to truncate the text from the leading edge (eg. "...lo, World!").

2 Answers

I believe using NSMutableParagraphStyle's lineBreakMode with NSMutableAttributedString might work

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

This gives something like this, which is what I think you want:

UITextField Leading Truncation iOS Swift

You just have to update the text attributes (e.g., defaultTextAttributes) with a .paragraphStyle with a lineBreakMode of .byTruncatingHead.

I would not just replace the .paragraphStyle, though. I would fetch it, update its lineBreakMode, and then update the text attributes with that:

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

Here it is with .byTruncatingHead, .byTruncatingMiddle and .byTruncatingTail, respectively:

enter image description here

Related