Space UIBarButtonItem 问题

Space issue with UIBarButtonItem

我正在尝试使用以下代码将 Cancel UIBarButtonItem 添加到我的导航栏:

func setupNavBar() {
    self.navBar = UINavigationBar(frame: CGRectMake(0.0, 0.0, UIScreen.mainScreen().bounds.width, 64.0))

    let customNavigationItem = UINavigationItem(title: "Connect Accounts")
    let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancelClicked")
    customNavigationItem.setLeftBarButtonItem(cancelButton, animated: true)

    self.navBar.setItems([customNavigationItem], animated: true)

    self.view.addSubview(self.navBar)
}

条形按钮完全贴在屏幕边缘,如下所示:

为什么这个按钮看起来粘在屏幕边缘,我怎样才能给它留出间距,这样它就不会粘在那里?请帮忙!

编辑:我的按钮粘在屏幕的左边缘而不是左上角。

试试这个

let btn = UIButton(frame: CGRectMake(<your margin>, 0, 50, 44))
        btn.setTitle("Cancel", forState: UIControlStateNormal)

       let btnbarButton = UIBarButtonItem(customView: btn)
        customNavigationItem.setLeftBarButtonItem(btnbarButton, animated: true)

试试吧。

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.setupNavBar()
    }
    func setupNavBar() {

        let navBar = UINavigationBar(frame: CGRectMake(0.0, 0.0, UIScreen.mainScreen().bounds.width, 64.0))
    let customNavigationItem = UINavigationItem(title: "Connect Accounts")
    let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancelClicked:")
    let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
    fixedSpace.width = 10
    customNavigationItem.leftBarButtonItems = [fixedSpace, cancelButton]

    navBar.setItems([customNavigationItem], animated: true)

    self.view.addSubview(navBar)
    }

    func cancelClicked(sender: AnyObject){
        print("Good luck!")
    }

添加 space 的正确方法是使用 .FixedSpace :

let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
fixedSpace.width = 10
customNavigationItem.leftBarButtonItems = [fixedSpace, cancelButton]

UIBarButtonSystemItemFixedSpace

Blank space to add between other items. Only the width property is used when this value is set.

Available in iOS 2.0 and later.