小编典典

导航栏按钮项目swift的图像

swift

我想在导航栏的左侧快速显示图像。

我尝试添加导航栏按钮项并在那里设置图像。

问题是我必须使用非常小的图像才能使其很好地适应导航栏。但是制作如此小的图像会导致像素化,特别是在较大的手机iPhone 6和6 Plus上。

有没有一种方法可以使用高质量的图像,然后将框架设置为适合导航栏的边界?

我的尝试:

var image = UIImage(named: "Harp.png")

image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
self.navigationItem.leftBarButtonItem.frame = CGRectMake(0, 0, 53, 31)
//image.frame = CGRectMake(0, 0, 53, 31)

我尝试先将框架放在图像上,然后再放在条形按钮项上。但这抛出了一个错误:

没有更多上下文的情况下,表达类型不明确。


阅读 199

收藏
2020-07-07

共1个答案

小编典典

试试这个

let button = UIButton(type: UIButtonType.Custom)
button.setImage(UIImage(named: "yourImageName.png"), forState: UIControlState.Normal)
button.addTarget(self, action:Selector("callMethod"), forControlEvents: UIControlEvents.TouchDragInside)
button.frame=CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.leftBarButtonItems = [newBackButton,barButton]

对于Swift 3

let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "yourImageName.png"), for: UIControlState.normal)
button.addTarget(self, action:#selector(ViewController.callMethod), for:.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) //CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem.init(customView: button)
            self.navigationItem.leftBarButtonItem = barButton

斯威夫特4

let button = UIButton(type: UIButton.ButtonType.custom)
button.setImage(UIImage(named: "getstarted"), for: .normal)
button.addTarget(self, action:#selector(callMethod), for: .touchDragInside)
button.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.leftBarButtonItems = [barButton]

这是行动

@objc func callMethod() {   
    //do stuff here
 }
2020-07-07