美文网首页
swif 4.1 自定义含有 subtitle 的 titleV

swif 4.1 自定义含有 subtitle 的 titleV

作者: _浅墨_ | 来源:发表于2018-10-21 13:30 被阅读31次
        // MARK:自定义 TitleView
        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 = UIColor.clear
            subtitleLabel.textColor = UIColor.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
        }
    

    调用方法,在 viewDidLoad() 中调用

    self.navigationItem.titleView = setTitle(title: "书架", subtitle: "已选择1本")
    
    效果图:
    custom titleView

    相关文章

      网友评论

          本文标题:swif 4.1 自定义含有 subtitle 的 titleV

          本文链接:https://www.haomeiwen.com/subject/eoqvzftx.html