Swift: как создать пользовательскую кнопку со значком программно

Чтобы программно создать пользовательскую кнопку со значком в Swift, вы можете использовать различные методы. Вот несколько подходов:

Метод 1: использование UIButton и UIImage

let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
let image = UIImage(named: "iconImageName")
button.setImage(image, for: .normal)
button.imageView?.contentMode = .scaleAspectFit
// Set additional button properties if needed
button.setTitle("Button Title", for: .normal)
button.setTitleColor(.black, for: .normal)
// Add target and action for button tap event
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
// Add the button to your view
self.view.addSubview(button)

Метод 2: использование UIBarButtonItem

let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
button.setImage(UIImage(named: "iconImageName"), for: .normal)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)
// Use the bar button item in your navigation bar or toolbar
navigationItem.rightBarButtonItem = barButtonItem

Метод 3: создание подкласса UIButton

class IconButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupButton()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupButton()
    }
    private func setupButton() {
        // Configure button properties
        setImage(UIImage(named: "iconImageName"), for: .normal)
        addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    }
}
// Usage:
let button = IconButton(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
button.setTitle("Button Title", for: .normal)
button.setTitleColor(.black, for: .normal)
// Add the button to your view
self.view.addSubview(button)

Это всего лишь несколько способов программного создания пользовательских кнопок со значками в Swift. Вы можете выбрать метод, который лучше всего соответствует вашим потребностям, и настроить кнопку по мере необходимости.