我在不使用Interface Builder的情况下制作应用程序,因此我正在通过代码创建所有内容。
我有一个嵌入在导航控制器中的视图控制器。我知道导航控制器有一个工具栏属性,我需要做的就是将布尔值设置为false以取消隐藏它。我的代码看起来像这样(它是一个在viewDidLoad中调用的函数):
func setUpToolBar(){
navigationController?.toolbarHidden = false
navigationController?.toolbar.barTintColor = UIColor.blackColor()
navigationController?.toolbar.tintColor = UIColor.whiteColor()
toolItems.append(addImageButton)
toolItems.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil))
toolItems.append(exportImageButton)
toolItems.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil))
toolItems.append(deleteImageButton)
navigationController?.toolbar.setItems(toolItems, animated: false)
}
以下是我为视图控制器声明这些属性的位置和方式:
private var addImageButton : UIBarButtonItem = {
let button = UIFactory.createBarButtonItem(nil, imageNamed: "plus button", style: .Plain, target: ImagesCollectionViewController.self, selector: #selector(ImagesCollectionViewController.addImage))
return button
}()
private var exportImageButton : UIBarButtonItem = {
let button = UIFactory.createBarButtonItem(nil, imageNamed: "export button", style: .Plain, target: ImagesCollectionViewController.self, selector: #selector(ImagesCollectionViewController.exportImagePressed))
return button
}()
private var deleteImageButton : UIBarButtonItem = {
let button = UIFactory.createBarButtonItem(nil, imageNamed: "trash button", style: .Plain, target: ImagesCollectionViewController.self, selector: #selector(ImagesCollectionViewController.deleteImagePressed))
return button
}()
private var toolItems : [UIBarButtonItem] = []
这是我的UIFactory类的函数,它只是处理在视图控制器之外创建这些UI项的麻烦
class func createBarButtonItem(title: String?, imageNamed : String?, style : UIBarButtonItemStyle?, target : AnyObject?, selector : Selector?) -> UIBarButtonItem{
let button = UIBarButtonItem()
if let theTitle = title {
button.title = theTitle
}
if let theImageName = imageNamed {
button.image = UIImage(named: theImageName)
}
if let theStyle = style{
button.style = theStyle
}
if let theTarget = target {
button.target = theTarget
}
if let theSelector = selector {
button.action = theSelector
}
return button
}
并且,在模拟器中运行此代码之后,这就是我所看到的(没有工具栏项目!另外,请注意我在该导航栏中有一个条形按钮项,我在代码中添加了很好)
请有人帮助我。我陷入了这样一个荒谬的步骤,没有这个我无法继续我的应用程序。
答案 0 :(得分:7)
只需删除
navigationController?.toolbar.setItems(toolItems, animated: false)
并把这行代码
self.toolbarItems = [toolItems]
答案 1 :(得分:1)
我改变了
navigationController!.toolbar.setItems(toolItems,animated:true)
到
toolbarItems = toolItems
并为我工作。