雖然有一個解決方案,但它在viewDidLoad
self.navigationItem.titleView = setTitle("Title", subtitle: "SubTitle")
一些已知問題
的解決辦法是寫一個函數這樣
func setTitle(title:String, subtitle:String) -> UIView {
let titleLabel = UILabel(frame: CGRectMake(0, -2, 0, 0))
titleLabel.backgroundColor = UIColor.clearColor()
titleLabel.textColor = UIColor.grayColor()
titleLabel.font = UIFont.boldSystemFontOfSize(17)
titleLabel.text = title
titleLabel.sizeToFit()
let subtitleLabel = UILabel(frame: CGRectMake(0, 18, 0, 0))
subtitleLabel.backgroundColor = UIColor.clearColor()
subtitleLabel.textColor = UIColor.blackColor()
subtitleLabel.font = UIFont.systemFontOfSize(12)
subtitleLabel.text = subtitle
subtitleLabel.sizeToFit()
let titleView = UIView(frame: CGRectMake(0, 0, max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), 30))
titleView.addSubview(titleLabel)
titleView.addSubview(subtitleLabel)
let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width
if widthDiff < 0 {
let newX = widthDiff/2
subtitleLabel.frame.origin.x = abs(newX)
} else {
let newX = widthDiff/2
titleLabel.frame.origin.x = newX
}
return titleView
}
使用此功能的自定義導航標題視圖只有已知的問題是,如果副標題變得比錯位發生的大。
最終結果
來源:https://gist.github.com/nazywamsiepawel/0166e8a71d74e96c7898
您是否嘗試過'self.navigationItem.prompt = 「字幕」'? – tktsubota
@tktsubota這將使標題上方的字幕,而不是標題 –
@RajanMaheshwari是的,我做了一個測試,發現了。 – tktsubota