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
}
This is how i'm setting title on navigationItem
self.navigationItem.titleView = setTitle(title: "DEMO NAME TO TEST TITLE", subtitle: "tap here to get info", animate: false)
How to fix that title with subTitle collapsing ? I don't mind showing "..." (no multiline) on title.