private func setTitle(title:String, subtitle:String, animate: Bool) -> UIView {
let titleLabel = UILabel(frame: CGRect(x:0, y:-5, width:0, height:0))
titleLabel.backgroundColor = UIColor.clear
titleLabel.textColor = UIColor.gray
titleLabel.font = UIFont.boldSystemFont(ofSize: 15)
titleLabel.text = title
titleLabel.adjustsFontSizeToFitWidth = true
let subtitleLabel = UILabel(frame: CGRect(x:0, y:18, width:0, height:0))
subtitleLabel.backgroundColor = UIColor.clear
subtitleLabel.textColor = UIColor.black
subtitleLabel.font = UIFont.systemFont(ofSize: 12)
subtitleLabel.text = subtitle
subtitleLabel.adjustsFontSizeToFitWidth = true
let titleView = UIView(frame: CGRect(x:0, y:0, width:max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), height:30))
let titleViewTapGesture = UITapGestureRecognizer(target: self, action: #selector(titleViewTapped(sender:)))
titleView.addGestureRecognizer(titleViewTapGesture)
titleView.addSubview(titleLabel)
if animate{
subtitleLabel.alpha = 0.0
titleView.addSubview(subtitleLabel)
UIView.animate(withDuration: 1) { () -> Void in
subtitleLabel.alpha = 1.0
}
}else{
titleView.addSubview(subtitleLabel)
}
let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width
if widthDiff > 0 {
var frame = titleLabel.frame
frame.origin.x = widthDiff / 2
titleLabel.frame = frame.integral
} else {
var frame = subtitleLabel.frame
frame.origin.x = abs(widthDiff) / 2
titleLabel.frame = frame.integral
}
return titleView
}
这就是我在navigationItem
self.navigationItem.titleView = setTitle(title: "DEMO NAME TO TEST TITLE", subtitle: "tap here to get info", animate: false)
如何通过subTitle折叠修复该标题?我不介意在标题上显示“......”(没有多行)。
答案 0 :(得分:4)
您可以使用以下功能实现此功能:
func setTitle(title:String, subtitle:String) -> UIView {
let titleLabel = UILabel(frame: CGRect(x: 0, y: -2, width: 0, height: 0))
titleLabel.backgroundColor = UIColor.clear
titleLabel.textColor = UIColor.gray
titleLabel.font = UIFont.boldSystemFont(ofSize: 17)
titleLabel.text = title
titleLabel.sizeToFit()
let subtitleLabel = UILabel(frame: CGRect(x:0, y:18, width:0, height:0))
subtitleLabel.backgroundColor = .clear
subtitleLabel.textColor = .black
subtitleLabel.font = UIFont.systemFont(ofSize: 12)
subtitleLabel.text = subtitle
subtitleLabel.sizeToFit()
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), height: 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
}
并且这样打电话:
self.navigationItem.titleView = setTitle(title: "Title Title Title", subtitle: "ello Shabir how are you")