导航栏按钮项目的图像 swift [英] image for nav bar button item swift

查看:17
本文介绍了导航栏按钮项目的图像 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

斯威夫特 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
 }

这篇关于导航栏按钮项目的图像 swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆