如何用swift设置条形按钮的图像?

时间:2014-12-16 07:58:51

标签: ios swift uiimage uibarbuttonitem

我正在尝试为条形图按钮设置图像,因为我有一个像这样的图像:

enter image description here

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

enter image description here

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

enter image description here

如果我尝试这样做就像为按钮创建一个IBOutlet并以编程方式设置Image this问题和代码:

 // 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)

但是没有任何事情发生,

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

或者哪种方式可以做到这一点?

14 个答案:

答案 0 :(得分:76)

我用这段代码以编程方式实现了这个目标:

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")
    }
}

结果将是:

enter image description here

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

self.navigationItem.leftBarButtonItem = barButton

结果将是:

enter image description here

如果您想要使用默认返回按钮返回导航控制器时的相同事务,那么您可以使用此代码使用自定义后退按钮实现此操作:

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

对于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")
    }
}

对于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")
    }
}

答案 1 :(得分:28)

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

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

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

答案 2 :(得分:19)

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

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

let button = UIButton()

以下是完整的解决方案,享受:(它比公认的解决方案更清洁)

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

答案 3 :(得分:15)

这是extension上的简单UIBarButtonItem

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
    }
}

答案 4 :(得分:9)

我正在使用最新的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

答案 5 :(得分:9)

只需要两行代码

Swift 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) 
{

}

答案 6 :(得分:5)

您的问题是因为图标的制作方式 - 它不符合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.

根据指南:

https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/BarIcons.html#//apple_ref/doc/uid/TP40006556-CH21-SW1

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

enter image description here

答案 7 :(得分:5)

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

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

答案 8 :(得分:3)

快速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
    }
}

答案 9 :(得分:1)

SwiftUI

.navigationBarItems修饰符可获取您想要的任何视图:

struct ContentView: View {
     var body: some View {
        NavigationView {
            Text("SwiftUI")
            .navigationBarItems(leading:
                HStack {
                    Image(systemName: "trash")
                    Text("Trash")
                }
            )
        }
    }
}

Leading with text[1]

.navigationBarItems(trailing: Image(systemName: "trash") )

Trailing

.navigationBarItems(leading: Image(systemName: "trash.fill"),
                    trailing: Image(systemName: "trash")
)

Bothsides

如果每个按钮都需要执行操作,则可以为每个按钮使用按钮。

答案 10 :(得分:0)

如果您的UIBarButtonItem已经像故事板中那样分配。 (printBtn)

    let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    btn.setImage(UIImage(named: Constants.ImageName.print)?.withRenderingMode(.alwaysTemplate), for: .normal)
    btn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handlePrintPress(tapGesture:))))
    printBtn.customView = btn

答案 11 :(得分:0)

按如下所示初始化barbuttonItem:

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

答案 12 :(得分:0)

如果在情节提要中设置了带有图像的UIBarButtonItem,则可以更改以下代码的一个小技巧是将以下代码添加到viewDidLoad()中。这样,您不必求助于在代码中添加整个按钮和图像。

if let navButton = self.navigationItem.leftBarButtonItem, let buttonImage = navButton.image {
    navButton.image = buttonImage.withRenderingMode(.alwaysOriginal)
}

答案 13 :(得分:0)

在Xcode中将图像添加到#go to contacts driver.get('https://app.nimble.com/#app/contacts/list') wait = WebDriverWait(driver, 20) wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, 'reactContactListFrame'))) element = wait.until(EC.element_to_be_clickable((By.XPATH, '//span[text()="call"]'))) element.click() 时只需选择Original image选项

enter image description here