ios 导航栏按钮项目 swift 的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31473359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:54:35  来源:igfitidea点击:

image for nav bar button item swift

iosswiftuinavigationcontrolleruibarbuttonitem

提问by user2363025

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.

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

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.

问题是我必须使用一个非常小的图像才能很好地适应导航栏。但是制作如此小的图像会导致像素化,尤其是在较大的 iPhone 6 和 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?

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

My attempt:

我的尝试:

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.

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

回答by Avijit Nagare

Try This

尝试这个

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]

For Swift 3

对于 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

Swift 4

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

Here is action

这是行动

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

回答by Mr.Javed Multani

Use this code:

使用此代码:

self.navigationItem.leftBarButtonItem = nil

let button = UIButton(type: .custom)
button.setImage(UIImage (named: "ChatTab"), for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
//button.addTarget(target, action: nil, for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)

let button2 = UIButton(type: .custom)
button2.setImage(UIImage (named: "ActivityTab"), for: .normal)
button2.frame = CGRect(x: 0.0, y: 0.0, width: 35.0, height: 35.0)
//button.addTarget(target, action: nil, for: .touchUpInside)

let barButtonItem2 = UIBarButtonItem(customView: button2)
self.navigationItem.rightBarButtonItems = [barButtonItem, barButtonItem2]

Output:enter image description here

输出:在此处输入图片说明

回答by elarctheitroadis

Swift 4 and 5:

斯威夫特 4 和 5:

let imageView = UIImageView(image: UIImage(named: "Harp"))
let buttonItem = UIBarButtonItem(customView: imageView)
self.navigationItem.leftBarButtonItem = buttonItem

回答by JoeFryer

There is a way to use images of different sizes, depending on the device. It's called an Asset Catalog. You'll probably already have one in your project, or if not, you can add one with File > New > File > Resource > Asset Catalogue.

有一种方法可以使用不同大小的图像,具体取决于设备。它被称为资产目录。您的项目中可能已经有一个,如果没有,您可以添加一个File > New > File > Resource > Asset Catalogue.

Within your Asset Catalog, you can have multiple 'Image Sets' (these will be shown down the left-hand side). Add a new Image Set with the '+' at the bottom. For each Image Set, you can supply different images (e.g. of different sizes) for each of @1x, @2x, and @3x.

在您的资产目录中,您可以拥有多个“图像集”(这些将显示在左侧)。添加一个底部带有“+”的新图像集。对于每个图像集,您可以为@1x、@2x 和@3x 中的每一个提供不同的图像(例如不同尺寸)。

Then, to use one of these images in code, you simply use UIImage(named: "name_of_image_set")- note no extension. The correct image will be loaded, depending on the device.

然后,要在代码中使用这些图像之一,您只需使用UIImage(named: "name_of_image_set")- 注意没有扩展名。将加载正确的图像,具体取决于设备。

Hope this helps!

希望这可以帮助!

回答by Doci

Swift 5, XCode 11 to make Navigation Bar Item with rounded image, image from assets or to download from URL.

Swift 5、XCode 11 使用圆形图像、来自资产的图像或从 URL 下载的导航栏项目。

1) New file: UIBarButtonItem+RoundedView.swift

1) 新文件:UIBarButtonItem+RoundedView.swift

import Foundation

class ImageBarButton : UIView {
    var imageView: UIImageView!
    var button: UIButton!

    convenience init(withUrl imageURL: URL? = nil, withImage image: UIImage? = nil, frame: CGRect = CGRect(x: 0, y: 0, width: 40, height: 40)) {
        self.init(frame: frame)

        imageView = UIImageView(frame: frame)
        imageView.backgroundColor = .white
        imageView.layer.cornerRadius = frame.height/2
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        addSubview(imageView)

        button = UIButton(frame: frame)
        button.backgroundColor = .clear
        button.setTitle("", for: .normal)
        addSubview(button)

        if let url = imageURL { // you can use pods like Nuke or Kingfisher 
         URLSession(configuration: .default).dataTask(with: URL(string: imageUrl)!) {[weak self] (data, response, error) in
          if let data = data , let image = UIImage(data: data) {
              DispatchQueue.main.async {
                self?.imgView.image = image
              }
           }
         }.resume()
        } else if let image = image {
            self.imageView.image = image
        }
    }

    func load()-> UIBarButtonItem {
        return UIBarButtonItem(customView: self)
    }
}

2) Add navigation bar items, you can use navigationItem.rightBarButtonItems, navigationItem.leftBarButtonItems:

2) 添加导航栏项,可以使用navigationItem.rightBarButtonItems, navigationItem.leftBarButtonItems

private func initalizeNavigationBarItems() {
    let searchBarButtonView = ImageBarButton(withImage: #imageLiteral(resourceName: "greenSearchIcon")) // Assets
    searchBarButtonView.button.addTarget(self, action: #selector(presentSearchViewController), for: .touchUpInside)

    if let user = AccountManager.currentUser, let userProfilePictureURL = user.imageUrl { // API Url
        let profileBarButtonView = ImageBarButton(withUrl: userProfilePictureURL)
        profileBarButtonView.button.addTarget(self, action: #selector(presentMoreViewController), for: .touchUpInside)
        navigationItem.rightBarButtonItems = [searchBarButtonView.load(), profileBarButtonView.load()]
    } else {
        let profileBarButtonView = ImageBarButton(withImage: #imageLiteral(resourceName: "profileIcon"))
        profileBarButtonView.button.addTarget(self, action: #selector(presentMoreViewController), for: .touchUpInside)
        navigationItem.rightBarButtonItems = [searchBarButtonView.load(), profileBarButtonView.load()]
    }
}

@objc func presentMoreViewController(_ sender: Any) {
    // present MoreViewController
}

@objc func presentSearchViewController(_ sender: Any) {
    // present SearchViewController
}

Preview

预览

enter image description here

在此处输入图片说明