【发布时间】:2017-06-15 17:52:26
【问题描述】:
我在运行时试图更改 UIBarButtonItem 类型的工具栏按钮时遇到了困难。
我已经为给定的文本视图以编程方式创建了一个工具栏,我想在按下按钮时更改按钮图像,就像它有一个图像切换和一个切换关闭一样。
我会解释:
我在这里创建带有所需按钮的工具栏
func configureToolbar(forTextView textView: UITextView) {
toolbar?.barStyle = UIBarStyle.default
toolbar?.items = [
UIBarButtonItem.init(image: UIImage.init(named: "bold_unselected"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.didTapBold(sender:))),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Italic", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.didTapItalic(sender:))),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Underline", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.dismissKB))]
toolbar?.sizeToFit()
for (index,item) in (toolbar?.items?.enumerated())! {
item.tag = index
}
// Adds a view as a upper border line
let border = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 0.5))
border.backgroundColor = UIColor.lightGray
toolbar?.addSubview(border)
// Configures the toolbar
toolbar?.backgroundColor = UIColor.white
toolbar?.barTintColor = UIColor.white
toolbar?.tintColor = UIColor.black
toolbar?.clipsToBounds = true
// Adds to the super view;
textView.inputAccessoryView = toolbar
}
这里是粗体按钮功能
func didTapBold(sender: UIBarButtonItem) {
typeface.isBold = typeface.isBold! ? false : true // true -> false -> true
toggleButton(button: sender, status: typeface.isBold!)
}
这里是我要更改按钮“状态”开-关的地方
func toggleButton(button: UIBarButtonItem, status: Bool) {
// changes the button appearance
switch button.tag {
case 0:
print("bold")
print("status \(status)")
if status {
button.image = UIImage.init(named: "bold_selected")
} else {
button.image = UIImage.init(named: "bold_unselected")
}
case 2:
print("bla bla bla")
case 4:
print("bla bla bla 2")
default:
print("default value called")
}
}
由于某种原因,我无法将图像更改为我想要的图像,但我可以更改为另一个图像。
我已阅读人机界面指南,但找不到推荐的工具栏图像尺寸,但搜索后我在某些网站上阅读了 20x20,有人可以确认吗?
有默认图片和选中图片之分。
更新 不知何故,我似乎无法向工具栏添加任何彩色图标/图像。刚刚尝试添加一个不同的图标,它只是显示为一个黑点。
【问题讨论】:
-
顺便说一句,我的图像/图标是 64x64 我不知道这是否导致了问题,我真的不这么认为
-
有人帮忙吗? :)
标签: ios swift3 uibarbuttonitem uitoolbar