导航栏按钮项目swift的图像 [英] image for nav bar button item swift
问题描述
我想在swift的导航栏左侧显示图像。
I want to display an image in the left hand side of my nav bar in swift.
我尝试添加导航栏按钮项并在那里设置图像。
I have tried adding a nav bar button item and setting an image there.
问题是我必须使用一个非常小的图像才能很好地适应导航栏。但制作如此小的图像会导致像素化,特别是在较大的手机iPhone 6和6 Plus上。
The problem is that I have to use a really small image for it to fit in the nav bar nicely. But making such a small image leads to pixelation especially on the bigger phone iPhone 6 and 6 Plus.
有没有办法使用高质量的图像然后设置框架适合导航栏的范围?
Is there a way to use a good quality image and then set the frame to fit within the bounds of the nav bar?
我的尝试:
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)
我尝试先将帧放在图像上然后再在栏按钮项目上。
但是这会引发一个错误:
I tried putting the frame on the image first and then on the bar button item. But this is throwing up an error:
表达式的含义不含更多上下文。
Type of expression is ambiguous without more context.
推荐答案
试试这个
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
这是行动
func callMethod() {
//do stuff here
}
这篇关于导航栏按钮项目swift的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!