Home > Software design >  UITextField: Leading Truncate
UITextField: Leading Truncate

Time:03-11

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!").

CodePudding user response:

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

  • Related