ios - Swift: 将 UIView 设置为 UIBarButton/UIButton 的背景

标签 ios swift uibutton uibarbuttonitem

如何将 UIView 设置为 UIBarButton 的背景? UIBarButton/UIButton 应该包含它的标题和背景图片。

我尝试覆盖 UIButton 类,但它不起作用。如果有人有解决方案,请告诉我。

最佳答案

// For UIBarButtonItem (just set customView parameter)

let frame = CGRect(x: 0, y: 0, width: 100, height: 40)
let customView = UIView(frame: frame)
customView.backgroundColor = .red

let barButtonItem = UIBarButtonItem(customView: customView)

// for UIButton

// 1. Subview case (add subview on your target UIButton, send to back so that it does not cover title)

let button0 = UIButton(frame: frame)
button0.addSubview(customView)
button0.sendSubviewToBack(customView)
button0.setTitle("Button", for: UIControl.State())

// 2. Rendered image case (as an alternative render your view to an image and add as a background image)

// Extension for capturing a UIVIew as an image:
extension UIImage {
    convenience init?(view: UIView) {
        UIGraphicsBeginImageContext(view.frame.size)
        guard let ctx = UIGraphicsGetCurrentContext() else {
            return nil
        }
        view.layer.render(in: ctx)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        guard let cgImage = image?.cgImage else {
            return nil
        }
        self.init(cgImage: cgImage)
    }
}

let button1 = UIButton(frame: frame)
let customViewImage = UIImage.init(view: customView)
button1.setBackgroundImage(customViewImage, for: UIControl.State())
button1.setTitle("Button", for: UIControl.State())

关于ios - Swift: 将 UIView 设置为 UIBarButton/UIButton 的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55235082/

相关文章:

swift - 带有 unowned 关键字的闭包保留了我的对象

ios - 如何响应 UIScrollView 中的 touchupinside 事件?

c++ - 如何在 iOS 的 openframeworks 中构建 3d 钻石

ios - 当应用程序从后台转到前台时,音乐将停止

ios - 错误 ITMS-90032 :"Invalid Image Path - No image found at the path referenced under key ' CFBundleIcons' :AppIcon40x40"

iphone - 如何监听 UIButton 状态变化?

ios - 如何禁用 UIButton 并发送 UIAlertView 消息

ios - 如何在用户触摸已选择的行时隐藏 UIPIckerView

swift - 在 Swift 中将 YouTube 视频添加到播放列表的 POST 请求

ios - UIButton、Mapbox、以编程方式打开新 View