【问题标题】:Space issue with UIBarButtonItemUIBarButtonItem 的空间问题
【发布时间】:2016-03-04 08:43:42
【问题描述】:

我正在尝试使用以下代码将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)
}

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

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

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

【问题讨论】:

标签: ios iphone swift uinavigationbar uibarbuttonitem


【解决方案1】:

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

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

UIBarButtonSystemItemFixedSpace

在其他之间添加空格 项目。设置此值时仅使用 width 属性。

适用于 iOS 2.0 及更高版本。

【讨论】:

  • 我昨天确实使用了您的答案,效果很好!发生的一件奇怪的事情是,今天我尝试删除该 fixedSpace 项目并且它工作正常。我完全不知道为什么会发生这种奇怪的事情。
  • 好的,我观察到,如果左右栏按钮项都设置了,那么间距就会显示正确,否则我们必须添加固定的空格栏按钮项!
【解决方案2】:

试试这个

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)

【讨论】:

    【解决方案3】:

    试试看。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      相关资源
      最近更新 更多