Создание динамических кнопок в Swift 4: несколько методов программного добавления кнопок

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

  1. Использование класса UIButton:

    let button = UIButton(type: .system)
    button.frame = CGRect(x: xPosition, y: yPosition, width: buttonWidth, height: buttonHeight)
    button.setTitle("Button Title", for: .normal)
    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    view.addSubview(button)
  2. Использование UIButton в качестве подкласса:

    class CustomButton: UIButton {
       // Custom implementation for the button
    }
    let button = CustomButton(type: .system)
    // Set button properties and add it to the view
  3. Использование UIStackView:

    let button = UIButton(type: .system)
    button.setTitle("Button Title", for: .normal)
    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    let stackView = UIStackView()
    stackView.axis = .vertical
    stackView.addArrangedSubview(button)
    // Add stackView to the view hierarchy

Это всего лишь несколько примеров. Есть и другие способы создания динамических кнопок в Swift. Не забудьте заменить xPosition, yPosition, buttonWidthи buttonHeightсоответствующими значениями в соответствии с вашими требованиями.