El Tomato El Tomato - 25 days ago 11
Swift Question

Subclassing UIViewController With NavigationBar Title

I'm trying to subclass a

UIViewController
with a label (
UILabel
) set to the title of the navigation bar. Instead of setting a name to self.title, I want to use an attributed string to set the title.

class BasicViewController: UIViewController {
var titleString = ""

func setup() {
//self.title = titleString
let navBar = navigationController!.navigationBar
navBar.barTintColor = UIColor.redColor()
let atext = NSMutableAttributedString(string: titleString)
atext.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSMakeRange(0, atext.length))
atext.addAttribute(NSStrokeColorAttributeName, value: UIColor.yellowColor(), range: NSMakeRange(0, atext.length))
atext.addAttribute(NSStrokeWidthAttributeName, value: NSNumber.init(float: -1.0), range: NSMakeRange(0, atext.length))
let titleLabel:UILabel = UILabel.init(frame: CGRectMake(50, 3, 220, 44))
titleLabel.attributedText = atext
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.font = UIFont(name: "Helvetica", size: 24.0)
}
}

class HomeViewController: BasicViewController {
override func viewDidLoad() {
super.viewDidLoad()
titleString = "My App"
setup()
}
}


If I run this code, I get an empty title. What am I doing wrong? Thanks.

Answer

I don't see where you're setting self.navigationItem.titleView = titleLabel

Comments