将右侧的 UIBarButton 移动到 UINavigationBar 的左侧 - Swift 2

Move the UIBarButton on the right side for the left side of the UINavigationBar - Swift 2

我正在开发一个出于设计原因需要使用对象 UINavigationBar 的应用程序。该项目完全以编程方式创建,情节提要中未创建任何内容。

创建了一个UINavigationBar和两个按钮,每个按钮都有一个动作:

我的问题与"move to the esquero side."有关,我把右边的东西"cut"(作为命令+ X)粘贴到左边。

我有什么:

我的屏幕是这样的:

我的swift代码是:

import UIKit

class ViewController: UIViewController {

    var frameSize: CGSize {
        get {
            return self.view.frame.size
        }
    }

    let navigationBar = UINavigationBar()
    var barButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationBar.frame.size = CGSize(width: frameSize.width, height: 64)
        navigationBar.frame.origin = CGPointZero
        navigationBar.items?.append(UINavigationItem(title: "NavBar"))

        self.view.addSubview(navigationBar)

        let button = UIButton(frame: CGRect(origin: CGPoint(x: 0, y: 100), size: CGSize(width: 320, height: 50)))
        button.titleLabel!.text = "Touch Me"
        button.titleLabel!.tintColor = .blueColor()
        button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "touchMe:"))
        button.backgroundColor = .purpleColor()
        self.view.addSubview(button)

        let button2 = UIButton(frame: CGRect(origin: CGPoint(x: 0, y: 200), size: CGSize(width: 320, height: 50)))
        button2.titleLabel!.text = "Touch Me 2"
        button2.titleLabel!.tintColor = .blueColor()
        button2.backgroundColor = .orangeColor()
        button2.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "touchMe2:"))
        self.view.addSubview(button2)

    }

    func action(sender: UIButton) {

        print("action")

    }

    func touchMe(sender:UITapGestureRecognizer) {

        barButton = UIBarButtonItem(title: "Right Button", style: .Plain, target: self, action: "action:")

        navigationBar.items?.first?.rightBarButtonItems?.append(barButton)

    }

    func touchMe2(sender:UITapGestureRecognizer) {

        navigationBar.items?.first?.leftBarButtonItem = barButton

    }

}

我的问题:

如何将右侧的 UIBarButton 移动到 UINavigationBar 的左侧?

有人可以帮助我吗?

感谢您的回答。

当您想将按钮从右侧移动到左侧时,您可以进行以下更改

func touchMe2(sender:UITapGestureRecognizer) {
    navigationBar.items?.first?.rightBarButtonItems?.removeFirst() // if you want to move first button.
    navigationBar.items?.first?.leftBarButtonItem = barButton
}

如果你想移动任意数字你可以使用removeAtIndex(index : Int)。 希望对您有所帮助。

也许……

    var yourButton:UIBarButtonItem = UIBarButtonItem(title: "Button", style: UIBarButtonItemStyle.Plain,target:self, action:"")

self.navigationItem.leftBarButtonItem = yourButton