导航栏按钮项目swift的图像

时间:2015-07-17 10:08:06

标签: ios swift uinavigationcontroller uibarbuttonitem

我想在swift的左侧显示一个图像。





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





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





有没有办法使用高质量的图像然后设置框架适合导航栏的范围?





我的尝试:




  var image = UIImage (名为:“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)
  




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





如果没有更多的上下文,表达式的类型是不明确的。




5 个答案:

答案 0 :(得分:45)

试试这个

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
}

答案 1 :(得分:4)

使用此代码:

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]

<强>输出: enter image description here

答案 2 :(得分:1)

根据设备的不同,有一种方法可以使用不同尺寸的图像。它被称为资产目录。您可能已经在项目中拥有一个,或者如果没有,您可以添加一个File > New > File > Resource > Asset Catalogue

在您的资产目录中,您可以拥有多个&#39;图像集&#39; (这些将显示在左侧)。使用&#39; +&#39;添加新的图像集在底部。对于每个图像集,您可以为@ 1x,@ 2x和@ 3x提供不同的图像(例如,不同大小)。

然后,要在代码中使用其中一个图片,只需使用UIImage(named: "name_of_image_set") - 请注意无扩展名。将加载正确的图像,具体取决于设备。

希望这有帮助!

答案 3 :(得分:1)

快速4和5:

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

答案 4 :(得分:0)

使用Swift 5,XCode 11制作带有圆形图像,资产图像或从URL下载的导航栏项。

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)添加导航栏项目,可以使用 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
}

预览

enter image description here