Search code examples
iosswiftuilabeluinavigationitem

Custom label navigation item does not work - Swift


I declared two variables:

var myString:NSString = "NavigationItemTitle"
var myMutableString = NSMutableAttributedString()

Next, in viewDidLoad() method:

 self.myMutableString = NSMutableAttributedString(string: self.myString as String, attributes: [NSFontAttributeName:UIFont(name: "Avenir", size: 18.0)!])
 self.myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:0,length:1))
 let label:UILabel = UILabel()
 label.attributedText = self.myMutableString
 self.navbar.topItem?.titleView = label

The result is that I see no navigation item, just an empty navigation bar. I suspect that there is something wrong with the last line with title view, because when I test something like this:

self.navbar.topItem?.title = "foo"

Navigation item is visible, however I can't apply any formatting in this way.

How to fix my code so the navigation item appears as custom label?


Solution

  • UILabel is an UIView subclass, and UIView designated initializer is `initWithFrame:.

    By initializing your label with UILabel(), the label has no frame and thus cannot be displayed. Instead replace this line with :

    let label:UILabel = UILabel(frame: CGRectMake(0, 0, 200, 40))
    

    (The width is set arbitrarily, the height works fine on 44px-tall navigation bar)