美文网首页demoSwift 专栏
swift微博第8天(自定义标题按钮)

swift微博第8天(自定义标题按钮)

作者: IIronMan | 来源:发表于2017-06-01 14:23 被阅读34次

    1.自定义一个TittleBtn

    import UIKit
    
    class TittleBtn: UIButton {
    
    // 初始化视图
       override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setTitleColor(UIColor.JKTextGayColor(), for: UIControlState.normal)
        setImage(UIImage(named:"navigationbar_arrow_down"), for: UIControlState.normal)
        setImage(UIImage(named:"navigationbar_arrow_up"), for: UIControlState.selected)
        sizeToFit()
        
       }
       // 防止storyboard崩溃
       required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
       }
    
       // 调整图片和文字的位置
       override func layoutSubviews() {
         super.layoutSubviews()
      
         titleLabel?.x = 0
         imageView?.x = titleLabel!.width
    
        }
    
    }
    

    提醒:我这里可以用.x.with是因为我对frame进行了重写

    2.调用自定义的标题按钮

       let btn = TittleBtn()
       btn.setTitle("极客江南 ", for: UIControlState.normal)
       btn.addTarget(self, action: #selector(HomeViewController.tittleClick(btn:)), for: UIControlEvents.touchUpInside)
       navigationItem.titleView = btn
    

    3.方法的实现

     @objc private func tittleClick(btn:TittleBtn){
    
        print("标题的点击方法")
        btn.isSelected = !btn.isSelected
    
    }

    相关文章

      网友评论

        本文标题:swift微博第8天(自定义标题按钮)

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