如何以编程方式为UIButton添加系统图标?

时间:2016-06-12 08:55:42

标签: ios swift uibutton

UIButton添加自定义图片或背景很容易,但似乎没有以编程方式为UIButton设置以下默认iOS图标之一,我知道它可以应用于导航栏按钮,我不需要,我想将它应用于简单的UIButton,任何提示?

enter image description here

5 个答案:

答案 0 :(得分:2)

对于Swift 5,语法为:

button.setImage(UIImage(systemName: "search"), for: .normal)

您还可以通过添加SymbolConfiguration来设置图标的权重:

let boldConfig = UIImage.SymbolConfiguration(weight: .bold)
let boldSearch = UIImage(systemName: "search", withConfiguration: boldConfig)

button.setImage(boldSearch, for: .normal)

请参阅:Apple documentation以获取可用名称(API列),或转到InterfaceBuilder,选择UIButton,然后在“属性检查器”中选择“图像”,该图像将为您提供所有可用图标的列表。

enter image description here

答案 1 :(得分:1)

import UIKit

extension UIImage {

    public convenience init?(_ systemItem: UIBarButtonItem.SystemItem) {

        guard let sysImage = UIImage.imageFrom(systemItem: systemItem)?.cgImage else {
            return nil
        }

        self.init(cgImage: sysImage)
    }

    private class func imageFrom(systemItem: UIBarButtonItem.SystemItem) -> UIImage? {

        let sysBarButtonItem = UIBarButtonItem(barButtonSystemItem: systemItem, target: nil, action: nil)

        //MARK:- Adding barButton into tool bar and rendering it.
        let toolBar = UIToolbar()
        toolBar.setItems([sysBarButtonItem], animated: false)
        toolBar.snapshotView(afterScreenUpdates: true)

        if  let buttonView = sysBarButtonItem.value(forKey: "view") as? UIView{
            for subView in buttonView.subviews {
                if subView is UIButton {
                    let button = subView as! UIButton
                    let image = button.imageView!.image!
                    return image
                }
            }
        }
        return nil
    }
}

这是我们如何使用它的示例:

 let button = UIButton() ;
 let systemImage = UIImage(systemItem: .trash) ;
 button.setImage(systemImage, for: .normal)

答案 2 :(得分:1)

我找到了 2521 个系统图标,作为数值。

@available(iOS 13.0, *)
@objc public extension UIImage{

    var assetName: String? {
        guard let imageAsset = imageAsset else { return nil }
        return imageAsset.value(forKey:"assetName") as? String
    }

    static var square_and_arrow_up: UIImage? {
        return UIImage(systemName: "square.and.arrow.up")
    }
    static var square_and_arrow_up_fill: UIImage? {
        return UIImage(systemName: "square.and.arrow.up.fill")
    }
    static var square_and_arrow_down: UIImage? {
        return UIImage(systemName: "square.and.arrow.down")
    }
    ...

截图: screenshot github:link

答案 3 :(得分:0)

现在您可以做

button.setImage(UIImage(.search), for: .normal)

答案 4 :(得分:-3)

来自Apple的文档:init(type:)