[英]Change Character spacing in navigation bar title swift
我想在導航欄標題中更改字符間距。 我想使用以下代碼。
let attributedString = NSMutableAttributedString(string: "New Title")
attributedString.addAttribute(NSKernAttributeName, value: CGFloat(1.4), range: NSRange(location: 0, length: 9))
self.navigationItem.title = attributedString
這會產生以下錯誤:
無法將類型為“NSMutableAttributedString”的值分配給“string?”類型的值
有人可以幫我這個或建議一種不同的方式來改變swift導航欄標題中的字符間距嗎?
您無法直接設置屬性字符串。
你可以通過替換titleView
來做一個技巧
let titleLabel = UILabel()
let colour = UIColor.redColor()
let attributes: [NSString : AnyObject] = [NSFontAttributeName: UIFont.systemFontOfSize(12), NSForegroundColorAttributeName: colour, NSKernAttributeName : 5.0]
titleLabel.attributedText = NSAttributedString(string: "My String", attributes: attributes)
titleLabel.sizeToFit()
self.navigationItem.titleView = titleLabel
Swift 4.2版本:
let titleLbl = UILabel()
let titleLblColor = UIColor.blue
let attributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: UIFont(name: "Noteworthy-Bold", size: 30)!, NSAttributedStringKey.foregroundColor: titleLblColor]
titleLbl.attributedText = NSAttributedString(string: "My Title", attributes: attributes)
titleLbl.sizeToFit()
self.navigationItem.titleView = titleLbl
請記住,Attributes字典中的NSAttributedStringKey.font
屬性遵循以下格式:
NSAttributedStringKey.font: UIFont(name: "FontNameILike-FontStyleILike", size: 30)!
FontName可以是你想要的任何東西,並且在iOS SDK中可用(我使用過Noteworthy)和一些標准字體樣式(我使用過Bold)如下:
Bold, BoldItalic, CondensedBlack, CondensedBold, Italic, Light, LightItalic, Regular, Thin, ThinItalic, UltraLight, UltraLightItalic
我希望以下博客文章也會有所幫助(截至2018年9月19日它仍然有效) https://medium.com/@dushyant_db/swift-4-recipe-using-attributed-string-in-navigation-bar-冠軍39f08f5cdb81
Ashish Kakkad的答案對於Swift 2來說是輕微失敗。使用NSString進行轉換時出錯。
所以正確的代碼是:
let titleLabel = UILabel()
let colour = UIColor.redColor()
let attributes: [String : AnyObject] = [NSFontAttributeName:UIFont.systemFontOfSize(12), NSForegroundColorAttributeName: colour, NSKernAttributeName : 5.0]
titleLabel.attributedText = NSAttributedString(string: "My String", attributes: attributes)
titleLabel.sizeToFit()
self.navigationItem.titleView = titleLabel
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.