如何在导航栏上添加按钮IOS swift

时间:2017-07-13 06:46:00

标签: ios swift

我的目标是在导航栏中间添加一个按钮

enter image description here

override func viewDidLoad() {
        super.viewDidLoad()
        // What should I add here?
    }

6 个答案:

答案 0 :(得分:2)

使用

SELECT 
a.*, c.FirstName, c.LastName, c.Email, c.Image, d.Name AS cityName,e.Name AS stateName, 
IF(a.Id = f.ListingId, "Y", "N") as Favourite 
FROM listings a
inner join listingimages b on a.Id = b.Listing
inner join rausers c on a.User = c.Id
inner join cities d on a.City = d.Id
inner join states e on a.State = e.Id
left join favlistings f on a.Id = f.listing
WHERE  a.Status="A" 
ORDER BY a.CreatedOn 
DESC LIMIT 20;

确保您的VC嵌入在UINavigationController中:)

答案 1 :(得分:1)

Swift 3.0

希望对你有所帮助。并且不要忘记将目标添加到UIButton

    let headerView = UIButton.init(frame: CGRect(x: 0, y: 0, width: 30, height: 25))
    headerView.setImage(UIImage(named: "btn_image.png"), for: .normal)
    headerView.addTarget(self, action: #selector(self.powerButtonTapped(_:)), for: .touchUpInside)
    self.navigationItem.titleView = headerView

像这样添加按钮操作:

func powerButtonTapped(_ sender: UIButton) {

    //Do your stuff here
}

答案 2 :(得分:0)

您必须将导航项标题视图设置为按钮对象

let powerButton =  UIButton(type: .custom)
powerButton.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
powerButton.setImage(UIImage(named: "power.png"), for: .normal)
powerButton.addTarget(self, action: #selector(self.clickOnPowerButton), for: .touchUpInside)
self.navigationItem.titleView = powerButton 

点击

func clickOnPowerButton(button: UIButton) {
   // do your stuffs
}

答案 3 :(得分:0)

let imageView = UIImageView(image: UIImage(named: "myImage"))
    imageView.contentMode = UIViewContentMode.scaleAspectFit
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    imageView.frame = titleView.bounds
    titleView.addSubview(imageView)
self.navigationItem.titleView = titleView

答案 4 :(得分:0)

使用titleView的{​​{1}}属性在导航栏的中央显示自定义视图。

自定义视图可以是按钮,因此您需要创建UINavigationItem并将其设置为UIButton

此处所需的代码在其他答案中给出,我会指向documentation。在实施之前阅读文档总是更好。

答案 5 :(得分:0)

  let lButton = UIButton()
        lButton.setTitle("Test Button", for: .normal)
        lButton.frame = CGRect(x:20, y: 0, width: self.view.frame.size.width - 50, height: 50)
        lButton.backgroundColor = UIColor.green
        lButton.setTitleColor(UIColor.red, for: .normal)
        lButton.addTarget(self, action: #selector(self.locationChangeAction), for: .touchUpInside)
       self.navigationController?.navigationBar.addSubview(lButton)