How do you limit UILabel characters in swift?

Krazyowl picture Krazyowl · Oct 6, 2015 · Viewed 11.7k times · Source

I'm trying to set a limit in my label to 10 characters, I'm a complete newbie to programming in general so its my 3rd month so far... anyway thanks in advance :-)

Answer

Juanes30 picture Juanes30 · Apr 12, 2019

You can also create a String extension and reuse it with any text string.. You can do it in the following way:

create the extension:

extension String {
   func maxLength(length: Int) -> String {
       var str = self
       let nsString = str as NSString
       if nsString.length >= length {
           str = nsString.substring(with:
               NSRange(
                location: 0,
                length: nsString.length > length ? length : nsString.length)
           )
       }
       return  str
   }
}

you can use the extension in the following way:

label.text = "This is a Very Long Label".maxLength(length: 10)

the previous code was tested in Swift 5.0