2017-12-14 5 views

Antwort

0

Sie sollten eine UILabel mit einem zugeschrieben Titel als benutzerdefinierte Titelansicht für Ihre Navigationsleiste.

let titleLabel = UILabel() 

//attributes for the first part of the string 
let firstAttr: [NSAttributedStringKey: Any] = [.font: UIFont.boldSystemFont(ofSize: 16), 
               .foregroundColor: UIColor.blue] 

//attributes for the second part of the string 
let secondAttr: [NSAttributedStringKey: Any] = [.font: UIFont.systemFont(ofSize: 16), 
               .foregroundColor: UIColor.red] 

//initializing the attributed string and appending the two parts together 
let attrString = NSMutableAttributedString(string: "Navigation", attributes: firstAttr) 
let secondAttrString = NSAttributedString(string: " Bar Title", attributes: secondAttr) 
attrString.append(secondAttrString) 

//setting the attributed string as an attributed text 
titleLabel.attributedText = attrString 

//finding the bounds of the attributed text and resizing the label accordingly 
let maxSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: .greatestFiniteMagnitude) 
titleLabel.frame.size = attrString.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, context: nil).size 

//setting the label as the title view of the navigation bar 
navigationItem.titleView = titleLabel 

Ergebnis:

navigation bar with custom title view

+0

danke. Ich verstehe es! – usinuniverse

0
try this 

NSDictionary *settings = @{ 
    UITextAttributeFont     : [UIFont fontWithName:@"YOURFONTNAME" size:20.0], 
    UITextAttributeTextColor   : [UIColor whiteColor], 
    UITextAttributeTextShadowColor  : [UIColor clearColor], 
    UITextAttributeTextShadowOffset  : [NSValue valueWithUIOffset:UIOffsetZero]}; 

[[UINavigationBar appearance] setTitleTextAttributes:settings]; 
+0

Ihnen danken. Ihre Antwort ist sauber. Die obige Antwort war jedoch etwas verständlicher. – usinuniverse

+0

Ja offensichtlich oben wird Ihnen besser zwei Probleme dienen: 1. Neue Kontrolle UILabel erstellt wird Verbrauch von Speicher 2 führen. Wenn Sie 100 View-Controller haben, wird 100 neues Etikett erstellt und der Titelansicht zugewiesen –

+0

Ich habe nicht darüber nachgedacht . Ich glaube, Du hast recht. Aber dein Code ist mir so unbekannt. Ist schnell richtig? – usinuniverse

Verwandte Themen