swiftuilabelcharacter-limit

How do you limit UILabel characters in swift?


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 :-)


Solution

  • If you want to limit the UILabel to just 10 characters then you just have to assign it with a text with length of 10. You can use NSString and NSRange to extract the text you need.

    let str = "This is a Very Long Label"
    let nsString = str as NSString
    if nsString.length >= 10
    {
      label.text = nsString.substringWithRange(NSRange(location: 0, length: nsString.length > 10 ? 10 : nsString.length))
    }