YogevSitton
YogevSitton

Reputation: 10108

UINavigationItem title truncation

I have text that is built from two Strings: A(B)

I want to use both strings as the title for the UINavigationItem but in case of truncation I want only A to be truncated and not B.

Example: The title I want is "The quick brown fox jumps (over the lazy dog)". The screen size is too small so the title truncates and it is now "The quick brown fox jumps (over...".

What I want it to be is: "The quick br... (over the lazy dog)"

How can I do that?

Upvotes: 2

Views: 1970

Answers (2)

bubibu
bubibu

Reputation: 324

Since xcode won't be able to detect in which part of your title you want to stop and which part you want to start again, you need to do it yourself.

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.title = "Heal the world make it a better place for you and for me and the entire human race"
    setNavTitle(title: self.navigationItem.title!)
}

func setNavTitle(title: String)
{
    //get the last 10 characters of your title, change the number to your need
    let last10 = title.substring(from:title.index(title.endIndex, offsetBy: -14))

    //get the first 10 characters of your title, change the number to your need
    let first10 = title.substring(to: title.index(title.startIndex, offsetBy: 14))

    //concatenate the strings
    let title = first10 + " ... " + last10
    self.navigationItem.title = title
}

Upvotes: 1

Sivajee Battina
Sivajee Battina

Reputation: 4174

First check number of characters navigation bar allowing as title without truncating. Next, before setting title check whether the total string length is less than those number of characters or not. Now based on condition set either combined string or B only.

Upvotes: 1

Related Questions