Чтобы динамически добавить кнопку в Swift 4, вы можете использовать несколько методов. Вот несколько подходов, которые вы можете использовать:
-
Использование класса 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)
-
Использование UIButton в качестве подкласса:
class CustomButton: UIButton { // Custom implementation for the button } let button = CustomButton(type: .system) // Set button properties and add it to the view
-
Использование 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
соответствующими значениями в соответствии с вашими требованиями.