ios 如何快速设置条形按钮的图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27499998/
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 04:02:25  来源:igfitidea点击:

How to set image for bar button with swift?

iosswiftuiimageuibarbuttonitem

提问by Dharmesh Kheni

I am trying to set an Image for bar button Item for that I have an image like:

我正在尝试为栏按钮项目设置一个图像,因为我有一个图像:

enter image description here

在此处输入图片说明

with resolution 30 * 30 but while I assign this Image to Bar button Its looks like:

分辨率为 30 * 30 但当我将此图像分配给条形按钮时它看起来像:

enter image description here

在此处输入图片说明

I have assigned image this way :

我以这种方式分配了图像:

enter image description here

在此处输入图片说明

and If I try this way like making an IBOutlet for the button and set Image programatically form thisquestion and code for that is:

如果我尝试这种方式,例如为按钮制作 IBOutlet 并以编程方式设置 Image 形成这个问题和代码是:

 // Outlet for bar button
 @IBOutlet weak var fbButton: UIBarButtonItem!

// Set Image for bar button
var backImg: UIImage = UIImage(named: "fb.png")!
fbButton.setBackgroundImage(backImg, forState: .Normal, barMetrics: .Default)

but nothing happend with this,

但没有发生任何事情,

Can anybody tell me what I am doing wrong?

谁能告诉我我做错了什么?

or which is the batter way to do this?

或者这是做到这一点的击球方式?

回答by Dharmesh Kheni

I have achieved that programatically with this code:

我已经使用以下代码以编程方式实现了这一目标:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        //set image for button
        button.setImage(UIImage(named: "fb.png"), forState: UIControlState.Normal)
        //add function for button
        button.addTarget(self, action: "fbButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
        //set frame
        button.frame = CGRectMake(0, 0, 53, 31)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    func fbButtonPressed() {

        println("Share to fb")
    }
}

And result will be:

结果将是:

enter image description here

在此处输入图片说明

Same way you can set button for left side too this way:

同样,您也可以通过这种方式为左侧设置按钮:

self.navigationItem.leftBarButtonItem = barButton

And result will be:

结果将是:

enter image description here

在此处输入图片说明

And if you want same transaction as navigation controller have when you go back with default back button then you can achieve that with custom back button with this code:

如果您希望在使用默认后退按钮返回时与导航控制器具有相同的事务,那么您可以使用以下代码通过自定义后退按钮实现:

func backButtonPressed(sender:UIButton) {
    navigationController?.popViewControllerAnimated(true)
}

For swift 3.0:

对于 Swift 3.0:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button = UIButton.init(type: .custom)
        //set image for button
        button.setImage(UIImage(named: "fb.png"), for: UIControlState.normal)
        //add function for button
        button.addTarget(self, action: #selector(ViewController.fbButtonPressed), for: UIControlEvents.touchUpInside)
        //set frame
        button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    func fbButtonPressed() {

        print("Share to fb")
    }
}

For swift 4.0:

对于 Swift 4.0:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button = UIButton(type: .custom)
        //set image for button
        button.setImage(UIImage(named: "fb.png"), for: .normal)
        //add function for button
        button.addTarget(self, action: #selector(fbButtonPressed), for: .touchUpInside)
        //set frame
        button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    @objc func fbButtonPressed() {

        print("Share to fb")
    }
}

回答by Anibal R.

An easy solution may be the following

一个简单的解决方案可能如下

barButtonItem.image = UIImage(named: "image")

then go to your Assets.xcassets select the image and go to the Attribute Inspector and select "Original Image" in Reder as option.

然后转到您的 Assets.xcassets 选择图像并转到属性检查器并在 Reder 中选择“原始图像”作为选项。

回答by jungledev

Similar to the accepted solution, but you can replace the

类似于已接受的解决方案,但您可以替换

let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton

with

let button = UIButton()

Here is the full solution, enjoy: (it's just a bit cleaner than the accepted solution)

这是完整的解决方案,享受:(它只是比公认的解决方案更干净)

let button = UIButton()
button.frame = CGRectMake(0, 0, 51, 31) //won't work if you don't set frame
button.setImage(UIImage(named: "fb"), forState: .Normal)
button.addTarget(self, action: Selector("fbButtonPressed"), forControlEvents: .TouchUpInside)

let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.rightBarButtonItem = barButton

回答by Jovan Stankovic

Here's a simple extensionon UIBarButtonItem:

这是一个简单extensionUIBarButtonItem

extension UIBarButtonItem {
    class func itemWith(colorfulImage: UIImage?, target: AnyObject, action: Selector) -> UIBarButtonItem {
        let button = UIButton(type: .custom)
        button.setImage(colorfulImage, for: .normal)
        button.frame = CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0)
        button.addTarget(target, action: action, for: .touchUpInside)

        let barButtonItem = UIBarButtonItem(customView: button)
        return barButtonItem
    }
}

回答by BSharer App - Share Books

I am using latest swift (2.1) and the answer (Dharmesh Kheni and jungledev) does not work for me. The image color was off (when setting in IB, it was blue and when setting directly in UIButton, it was black). It turns out I could create the same bar item with the following code:

我正在使用最新的 swift (2.1) 并且答案(Dharmesh Kheni 和jungledev)对我不起作用。图像颜色关闭(在 IB 中设置时为蓝色,直接在 UIButton 中设置时为黑色)。事实证明,我可以使用以下代码创建相同的栏项目:

let barButton = UIBarButtonItem(image: UIImage(named: "menu"), landscapeImagePhone: nil, style: .Done, target: self, action: #selector(revealBackClicked))
self.navigationItem.leftBarButtonItem = barButton

回答by Sreekumar .K

Only two Lines of code required for this

这个只需要两行代码

Swift 3.0

斯威夫特 3.0

let closeButtonImage = UIImage(named: "ic_close_white")
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: closeButtonImage, style: .plain, target: self, action:  #selector(ResetPasswordViewController.barButtonDidTap(_:)))

func barButtonDidTap(_ sender: UIBarButtonItem) 
{

}

回答by Mr.Javed Multani

You can use this code for multiple bar button with custom image:

您可以将此代码用于具有自定义图像的多个条形按钮:

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]

Result will be this:

结果将是这样的:

enter image description here

在此处输入图片说明

回答by aparna

Your problem is because of the way the icon has been made - it doesn't conform to Apple's custom tab bar icon specs:

您的问题是由于图标的制作方式 - 它不符合 Apple 的自定义标签栏图标规范:

To design a custom bar icon, follow these guidelines:

要设计自定义栏图标,请遵循以下准则:

  • Use pure white with appropriate alpha transparency.
  • Don't include a drop shadow.
  • Use antialiasing.
  • 使用具有适当 alpha 透明度的纯白色。
  • 不要包含阴影。
  • 使用抗锯齿。

(From the guidelines.)

(来自指南。)

Something that would be possible looks like this. You can find such icons on most free tab bar icon sites.

可能的事情看起来像这样。您可以在大多数免费标签栏图标网站上找到此类图标。

Button example

按钮示例

回答by Eric Ford

Initialize barbuttonItem like following:

像下面这样初始化 barbuttonItem:

let pauseButton = UIBarButtonItem(image: UIImage(named: "big"),
                                  style: .plain,
                                  target: self,
                                  action: #selector(PlaybackViewController.pause))

回答by Исмаил Хасбулатов

Swift 4.

斯威夫特 4.

@IBOutlet weak var settingBarBtn: UIBarButtonItem! {
    didSet {
        let imageSetting = UIImageView(image: UIImage(named: "settings"))
        imageSetting.image = imageSetting.image!.withRenderingMode(.alwaysOriginal)
        imageSetting.tintColor = UIColor.clear
        settingBarBtn.image = imageSetting.image
    }
}