簡體   English   中英

Swift:將UIView設置為UIBarButton / UIButton的背景

[英]Swift: Set UIView as the background of UIBarButton/UIButton

如何將UIView設置為UIBarButton的背景? UIBarButton/UIButton應包含其標題和背景圖像。

我嘗試覆蓋UIButton類,但是它不起作用。 如果有人有解決方案,請告訴我。

您可以將視圖添加為按鈕的subView

extension UIButton {
    func setBackgroundView(view: UIView) {
        view.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
        view.isUserInteractionEnabled = false
        self.addSubview(view)
    }
}
// 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())

您可以使用從UIControl繼承的CustomButton。 通過使用xib,您可以根據需要管理UI。 您可以在其中添加n個UI元素。 您將獲得帶有UIButton之類的默認事件處理程序(如touchupinside,touchupoutside,valuechange)。 您可以提供相同的IBAction。 作為參考,請附上一些屏幕截圖。 讓我知道您在執行此操作時是否遇到任何困難。 繼續編碼。

添加XIB

添加UIControl的子類並管理IBOut

管理事件

也許您應該使用UIImageView.image而不是UIView本身來設置底部的背景圖像。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myButton: UIButton!
    @IBOutlet weak var myView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        myButton.setBackgroundImage(myView.image, for: .normal)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM