如何在导航栏Swift右侧添加自定义视图? [英] How to add custom view on right of navigation bar Swift?

查看:283
本文介绍了如何在导航栏Swift右侧添加自定义视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 UINavigationBar 右侧添加 自定义视图 。我尝试的是以下内容,但视图没有显示出来!请帮助,提前谢谢!

I am trying to add a custom view on right of UINavigationBar. What I tried is the following, but the view is not showing up! Please help, thanks in advance!

let viewOnrightButton = UIView(frame: CGRect(x: 2, y: 2, width: 60, height: 22))
 // viewOnrightButton.frame = CGRectMake(2, 2, 60, 22)
viewOnrightButton.layer.cornerRadius = 2
viewOnrightButton.backgroundColor = UIColor(red: 0.961, green: 0.827, blue: 0.239, alpha: 1.00)

lblNumbersOfBanana.frame = CGRectMake(2, 1, viewOnrightButton.frame.width-20, 20)
lblNumbersOfBanana.text = "001"

var bananaImgView = UIImageView(frame: CGRect(x: viewOnrightButton.frame.width-22, y: 0, width: 20, height: 20))
 //  bananaImgView.frame = CGRectMake(viewOnrightButton.frame.width-22, 0, 20, 20)
bananaImgView.image = UIImage(named: "banana")

viewOnrightButton.addSubview(lblNumbersOfBanana)
viewOnrightButton.addSubview(bananaImgView)

self.navigationItem.rightBarButtonItem?.customView = viewOnrightButton


推荐答案

//创建uiview并添加thre e自定义按钮

// creating uiview and add three custom buttons

 func addRightButton(){

    let viewFN = UIView(frame: CGRectMake(0, 0, 180,40))
        viewFN.backgroundColor = UIColor.yellowColor()
    let button1 = UIButton(frame: CGRectMake(0,8, 40, 20))
    button1.setImage(UIImage(named: "notification"), forState: UIControlState.Normal)
    button1.setTitle("one", forState: .Normal)

    button1.addTarget(self, action: #selector(self.didTapOnRightButton), forControlEvents: UIControlEvents.TouchUpInside)

    let button2 = UIButton(frame: CGRectMake(40, 8, 60, 20))
    button2.setImage(UIImage(named: "notification"), forState: UIControlState.Normal)
    button2.setTitle("tow", forState: .Normal)
    let button3 = UIButton(frame: CGRectMake(80, 8, 60, 20))
     button3.setImage(UIImage(named: "notification"), forState: UIControlState.Normal)
    button3.setTitle("three", forState: .Normal)

    button3.addTarget(self, action: #selector(self.didTapOnRightButton), forControlEvents: UIControlEvents.TouchUpInside)

    viewFN.addSubview(button1)
    viewFN.addSubview(button2)
    viewFN.addSubview(button3)


    let rightBarButton = UIBarButtonItem(customView: viewFN)
    self.navigationItem.rightBarButtonItem = rightBarButton

}

这篇关于如何在导航栏Swift右侧添加自定义视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆