ios swift 导航栏左按钮自定义

本文介绍了如何在Swift中自定义导航栏的左按钮,包括设置不同类型(仅标题、仅图片、有图有标题、无图无标题),使用block回调,以及懒加载和按钮点击方法的实现。
摘要由CSDN通过智能技术生成

swift 导航栏左按钮自定义

1、设置类型

enum YDBarItemTypeType:Int {

    caseOnlyHaveImage=0          // default 仅有图

    caseOnlyHaveTitle=1          // 仅有标题

    case HaveImageAndImage = 2      // 有图有标题

    case NotImageAndImage = 3      // 无图无标题

}

2、写一个block按钮回调方法

// Mark: -数据源更新

    typealias NavBtnClickBlock = () ->Void

    var leftBtnBlock:NavBtnClickBlock?

3、然后创建一个按钮懒加载

//Mark: - 导航栏左边按钮

    private lazy var leftBarButton:UIButton = {

        letbutton =UIButton.init(type:UIButton.ButtonType.custom)

        button.frame=CGRect(x:0,y:0,width:30,height:30)

        button.addTarget(self,action:#selector(leftBarButtonClick),for:UIControl.Event.touchUpInside)

        returnbutton

    }()

4、按钮点击方法实现

 //Mark: - 导航栏左边消息点击事件

    @objc func leftBarButtonClick() {

        if((self.leftBtnBlock) !=nil){

            self.leftBtnBlock!()

        }

    }

5、调用方法

func setNavigationLeftBarItemType(type:YDBarItemTypeType,title:String,image:String,color:UIColor,block:@escaping NavBtnClickBlock){

        leftBtnBlock= block

        leftBarButton.setTitleColor(color,for:UIControl.State.normal)

        if(type == YDBarItemTypeType.OnlyHaveTitle){

            leftBarButton.setTitle(title,for:UIControl.State.normal)

            leftBarButton.setImage(UIImage(),for:UIControl.State.normal)

        }else if(type == YDBarItemTypeType.OnlyHaveImage){

            leftBarButton.setTitle("",for:UIControl.State.normal)

            leftBarButton.setImage(UIImage(named: image),for:UIControl.State.normal)

        }else if(type == YDBarItemTypeType.HaveImageAndImage){

            leftBarButton.setTitle(title,for:UIControl.State.normal)

            leftBarButton.setImage(UIImage(named: image),for:UIControl.State.normal)

        }else if(type == YDBarItemTypeType.NotImageAndImage){

            leftBarButton.setTitle("",for:UIControl.State.normal)

            leftBarButton.setImage(UIImage(),for:UIControl.State.normal)

        }else{

            leftBarButton.setTitle(title,for:UIControl.State.normal)

            leftBarButton.setImage(UIImage(named: image),for:UIControl.State.normal)

        }

        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftBarButton)

    }

6、在viewDidLoad中调用方法

setNavigationLeftBarItemType(type: YDBarItemTypeType.OnlyHaveImage,title: "", image: "back_allow",color: UIColor.white, block: {

            self.pop()

        })
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玉笛0114

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值