How to add system icons for a UIButton programmatically?

前端 未结 4 1340
野趣味
野趣味 2021-02-19 10:54

It\'s easy to add a custom image or a background for a UIButton , but there seems to be no programmatic way to set one of the following default iOS icons for a

4条回答
  •  情话喂你
    2021-02-19 11:32

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

    This is an example of how do we use it:

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

提交回复
热议问题