UIBarButtonItem的空间问题

时间:2016-03-04 08:43:43

标签: ios iphone swift uinavigationbar 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)
}

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

enter image description here

为什么这个按钮出现在屏幕的边缘,我怎么能给它留出间距以免它粘在那里?请帮忙!

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

3 个答案:

答案 0 :(得分:1)

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

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

UIBarButtonSystemItemFixedSpace

     

在其他之间添加的空白区域   项目。设置此值时,仅使用width属性。

     

适用于iOS 2.0及更高版本。

答案 1 :(得分:0)

试试这个

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)

答案 2 :(得分:0)

试试吧。

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!")
    }