不能用UIToolBar制作带有白色按钮项目色调的黑色(ios 9,Swift)

时间:2016-01-19 17:46:32

标签: swift ios9 xcode7 uitoolbar

我以编程方式将工具栏添加到UIPickerView,以便我可以进行"完成"按钮,我想让UIToolBar变黑,条形项目变白。文档说如果你想要一个不透明的UIToolBar,你必须将它的半透明度设置为false并将barStyle设置为黑色。我已经完成了这个,UIToolBar仍然是白色的。

private func pickerViewSetup() {

    let pickerView = UIPickerView()
    pickerView.delegate = self
    pickerView.dataSource = self
    pickerView.backgroundColor = .whiteColor()
    pickerView.showsSelectionIndicator = true

    let toolBar = UIToolbar()
    toolBar.translucent = false
    toolBar.barStyle = .Black

    let doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: "donePicker")
    doneButton.tintColor = UIColor.whiteColor()

    let flexibleSpaceItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: "Flexible Space")

    toolBar.setItems([flexibleSpaceItem, doneButton], animated: false)
    toolBar.userInteractionEnabled = true

    pickerTextField.inputView = pickerView
    pickerTextField.inputAccessoryView = toolBar
}

4 个答案:

答案 0 :(得分:5)

感谢u84six的回答。你可以这样做:

toolBar.tintColor = UIColor.whiteColor()//"Done" button colour
toolBar.barTintColor = UIColor.blackColor()// bar background colour 
toolBar.sizeToFit()// Very important, the barTintColor will not work without this         

答案 1 :(得分:4)

我需要做的就是添加调用toolBar.sizeToFit()并修复所有颜色问题。这是完整的工作代码:

private func pickerViewSetup() {

    let pickerView = UIPickerView()
    pickerView.delegate = self
    pickerView.dataSource = self
    pickerView.backgroundColor = .whiteColor()
    pickerView.showsSelectionIndicator = true

    let toolBar = UIToolbar()
    toolBar.barStyle = UIBarStyle.Black
    toolBar.tintColor = UIColor.whiteColor()
    toolBar.sizeToFit()

    let doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: "donePicker")
    let flexibleSpaceItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: "Flexible Space")

    toolBar.setItems([flexibleSpaceItem, doneButton], animated: false)
    toolBar.userInteractionEnabled = true

    pickerTextField.inputView = pickerView
    pickerTextField.inputAccessoryView = toolBar
}

答案 2 :(得分:0)

toolBar不是所需的颜色,因为toolBar.backgroundColor未正确设置。使用

将其设置为BlackColor
toolBar.backgroundColor = UIColor.BlackColor()

答案 3 :(得分:0)

这还不够。添加

toolBar.backgroundColor = UIColor.BlackColor();