我想在我的导航栏的左侧显示一个图像.
我已经尝试添加导航栏按钮项目并在那里设置图像.
问题是,我必须使用一个非常小的图像,以适应在导航栏很好.但是制作这样一个小小的图像会导致像素化,特别是在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,53,31) //image.frame = CGRectMake(0,31)
我尝试先将框架放在图像上,然后再将其放在条形按钮上.
但是这是一个错误:
没有更多上下文的表达式是不明确的.
解决方法
尝试这个
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,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: UIControlEvents.touchUpInside) button.frame = CGRect.init(x: 0,y: 0,width: 30,height: 30) //CGRectMake(0,30) let barButton = UIBarButtonItem.init(customView: button) self.navigationItem.leftBarButtonItem = barButton
这是行动
func callMethod() { //do stuff here }