我想在导航栏按钮中添加图片。
这是我要设置的图片:
我将bar button
拖到Main.storyboard
进行设置。然后我这样设置:
@IBOutlet var addNewNoteButton: UIBarButtonItem!
...
let featherImageView = UIImageView()
featherImageView.contentMode = UIViewContentMode.ScaleAspectFit
featherImageView.image = UIImage(named: "feather")?.imageWithRenderingMode(.AlwaysOriginal)
addNewNoteButton.image = featherImageView.image
但它没有很好地显示图像:
我也看到了某处,但他们只创建了一个按钮,然后将此按钮指定给导航栏按钮。
任何帮助都将不胜感激。
答案 0 :(得分:5)
您可以为此创建自定义按钮。在viewDidLoad
方法中使用以下代码。
//create a new button
let button: UIButton = UIButton(type: .Custom)
//set image for button
button.setImage(UIImage(named: "T018d.png"), forState: UIControlState.Normal)
//set frame
button.frame = CGRectMake(0, 0, 53, 31)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
结果将是:
如果您想将其放在左侧,请更换此行
self.navigationItem.rightBarButtonItem = barButton
带
self.navigationItem.leftBarButtonItem = barButton
答案 1 :(得分:2)
解决方案Swift 4:
let barButton = UIButton()
self.backButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
backButton.setImage(UIImage(named: "image"), for: .normal)
backButton.setImage(UIImage(named: "image"), for: .highlighted)
backButton.imageView?.contentMode = .scaleAspectFit
backButton.addTarget(self, action: #selector(PresenterBaseViewController.backAction(_:)), for: .touchUpInside)
barButton.addSubview(self.backButton)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: barButton)
答案 2 :(得分:0)
尝试
let addNewNoteButtonImage = UIImage(named: "feather")?.imageWithRenderingMode(.AlwaysOriginal)
addNewNoteButton.image = addNewNoteButtonImage
addNewNoteButton.contentMode = UIViewContentMode.ScaleAspectFit
答案 3 :(得分:0)
如果你想在UIButton中设置UIImage的内容模式,你必须访问带有的按钮imageView:
button(UIImage(named: "feather"), forState: .Normal)
button?.contentMode = .ScaleAspectFit