Swift UIToolBar追加UIBarButtonItem项目

我没有得到正确的语法。 有人知道这里缺less什么吗? 我正在使用Xcode 6testing版3,我试图dynamic地添加一个工具栏项目到我的(手动添加)在我的viewDidLoad工具栏。 有两个问题。 首先,我不能将我的工具栏中的项目添加到数组中。 其次,编译器允许我的调用追加(+ =),当它完成时,数组仍然是空的。

override func viewDidLoad() { super.viewDidLoad() var items = [AnyObject]() // Zero items, mutable, right? // items += buttonBar.items // Not allowed --> compiler error if let displayModeButton = self.splitViewController.displayModeButtonItem() { items += displayModeButton // Still zero items after append } buttonBar.items = items // Still zero items after append } 

buttonBar是在IB中设置的IBOutlet。

我能够通过强制展开数组来添加工具栏的项目。 看来这不应该是必要的,因为items属性是隐式地展开的,但是这使编译器能够通过它。

我不知道为什么你的items += displayModeButton行不工作 – 你确定它被称为? 此代码添加一个标题为“Another”的button到我的工具栏中:

 var items = [AnyObject]() items += self.barButton.items! items += UIBarButtonItem(title: "Another", style: .Plain, target: nil, action: "") self.barButton.items = items 

下面的代码为我工作:

  let keyboardDoneButtonView = UIToolbar() keyboardDoneButtonView.sizeToFit() let flexBarButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil) let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("doneClicked")) var items = [UIBarButtonItem]() items.append(flexBarButton) items.append(doneButton) keyboardDoneButtonView.items = items 

希望这可以帮助!!