navigationItem的手动设定titleview的不神韵:垂直
问题描述:
我使用的是扩展UIViewController
这里面FUNC添加用于调整字体,以适应宽度的标题。navigationItem的手动设定titleview的不神韵:垂直
extesion UIViewController {
func setTitleDifferentSizes(title: String){
self.title = title
guard let navigationBarHeight: CGFloat =
self.navigationController?.navigationBar.frame.height else{
return
}
let tlabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width:
200.0, height: navigationBarHeight))
tlabel.text = self.title
tlabel.textColor = UIColor.white
tlabel.font = font24
tlabel.backgroundColor = UIColor.clear
tlabel.adjustsFontSizeToFitWidth = true
self.navigationItem.titleView = tlabel
}
}
我从这个SO问题,这个解决方案,改变了一点点: How to resize Title in a navigation bar dynamically
现在我的问题是,标题的文本不垂直对齐到其他的导航栏项目,你可以在图像中看到的,我告诉一个,我刚安装的称号,而无需使用上面的方法,以及文本有可能不适合,但它是正确对齐,以及其他图像是使用上述方法,其中文本适合,但它不对齐。
答
试试这个: -
func setTitleDifferentSizes(title: String){
self.title = title
guard let navigationBarHeight: CGFloat =
self.navigationController?.navigationBar.frame.height else{
return
}
let attributedString = NSMutableAttributedString(string: title)
let myAttribute = [ NSForegroundColorAttributeName: UIColor.white ,NSFontAttributeName: font24]
attributedString.addAttributes(myAttribute, range: NSRange(location: 0, length: attributedString.string.characters.count))
attributedString.addAttributes([NSBaselineOffsetAttributeName:6.0], range: NSRange(location: 0, length: title.characters.count)
)
let tlabel = UILabel(frame: CGRect(x: 0.0, y: 0.0, width:
200.0, height: navigationBarHeight))
tlabel.attributedText = attributedString
tlabel.backgroundColor = UIColor.clear
tlabel.adjustsFontSizeToFitWidth = true
tlabel.minimumScaleFactor = 0.2
tlabel.textAlignment = .center
self.navigationItem.titleView = tlabel
}
如果要调整文本的位置,请更改NSBaselineOffsetAttributeName的浮点值设置垂直对齐
。