如何以编程方式创建按钮

如何以编程方式创建按钮

本文介绍了如何以编程方式创建按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift中以编程方式创建图形元素(如 UIButton )?我试图在视图中创建并添加按钮,但无法进行。

How do I programmatically create graphical elements (like a UIButton) in Swift? I tried to create and add button into a view, but wasn't able to.

推荐答案

这是一个完整的添加解决方案一个 UIButton 以编程方式使用 targetAction

Swift 2.2

Here is a complete solution to add a UIButton programmatically with the targetAction.
Swift 2.2

override func viewDidLoad() {
  super.viewDidLoad()

  let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
  button.backgroundColor = .greenColor()
  button.setTitle("Test Button", forState: .Normal)
  button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)

  self.view.addSubview(button)
}

func buttonAction(sender: UIButton!) {
  print("Button tapped")
}

最好使用 NSLayoutConstraint 而不是 frame 来正确放置按钮对于每个iPhone屏幕。

It is probably better to use NSLayoutConstraint rather than frame to correctly place the button for each iPhone screen.

更新了鳕鱼e到 Swift 3.1

override func viewDidLoad() {
  super.viewDidLoad()

  let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
  button.backgroundColor = .green
  button.setTitle("Test Button", for: .normal)
  button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

  self.view.addSubview(button)
}

func buttonAction(sender: UIButton!) {
  print("Button tapped")
}

这篇关于如何以编程方式创建按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 00:38