theDC
theDC

Reputation: 6484

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?

Upvotes: 2

Views: 2354

Answers (3)

Shubham bairagi
Shubham bairagi

Reputation: 953

yes if you adding any subview you need to set frame for it

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

Upvotes: 1

Nimit Parekh
Nimit Parekh

Reputation: 16864

Please try following code.

class ViewController: UIViewController {

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

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    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 titleLabel = UILabel(frame: CGRectMake(0, 0, view.frame.size.width - 120, 44))
    titleLabel.attributedText = self.myMutableString
    titleLabel.backgroundColor = UIColor.clearColor()
    titleLabel.textAlignment = NSTextAlignment.Center

    self.navigationController!.navigationBar.topItem!.titleView = titleLabel
    }

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Need to set the width of UILabel.

let titleLabel = UILabel(frame: CGRectMake(0, 0, view.frame.size.width - 120, 44))

Upvotes: 1

Michaël Azevedo
Michaël Azevedo

Reputation: 3896

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)

Upvotes: 3

Related Questions