我如何以编程方式创建图形元素(如UIButton)在Swift?我试图创建和添加按钮到一个视图,但不能。


当前回答

我通常会设置uibutton的扩展。斯威夫特5。

let button: UIButton = UIButton()
override func viewDidLoad() {
        super.viewDidLoad()
     button.setup(title: "OK", x: 100, y: 430, width: 220, height: 80, color: .yellow)
        buttonD.setTitleColor(.black, for: .normal)

}
extension UIButton {
    func setup(title: String, x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor){
        frame = CGRect(x: x, y: y, width: width, height: height)
        backgroundColor = color
        setTitle(title , for: .normal) 
        }
    }

其他回答

是的,在模拟器里。有时它不会识别选择器,这似乎是一个错误。即使我面对的不是你的代码,然后我只是改变了动作名称(选择器)。它的工作原理

let buttonPuzzle:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
buttonPuzzle.backgroundColor = UIColor.greenColor()
buttonPuzzle.setTitle("Puzzle", forState: UIControlState.Normal)
buttonPuzzle.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
buttonPuzzle.tag = 22;
self.view.addSubview(buttonPuzzle)

选择器函数在这里:

func buttonAction(sender:UIButton!)
{

    var btnsendtag:UIButton = sender
    if btnsendtag.tag == 22 {            
        //println("Button tapped tag 22")
    }
}

从storyboard创建UIButton: 1 -将UIButton对象从对象库拖到storyboard文件中的ViewController 2 -节目助理编辑 3 -从上面创建的UIButton中右键拖动到你的类中。结果如下:

@IBAction func buttonActionFromStoryboard(sender: UIButton)
{
    println("Button Action From Storyboard")
}

为创建UIButton编程: 1-写入“override func viewDidLoad()”:

        let uiButton    = UIButton.buttonWithType(UIButtonType.System) as UIButton
        uiButton.frame  = CGRectMake(16, 116, 288, 30)
        uiButton.setTitle("Second", forState: UIControlState.Normal);
        uiButton.addTarget(self, action: "buttonActionFromCode:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(uiButton)

2-添加IBAction功能:

@IBAction func buttonActionFromCode(sender:UIButton)
{
    println("Button Action From Code")
}
 var sampleButton:UIButton?

 override func viewDidLoad() {
  super.viewDidLoad()

 }
 override func viewDidAppear(animated: Bool) {

  sampleButton = UIButton(type: .RoundedRect)
  //sampleButton.frame = CGRect(x:50, y:500, width:70, height:50)

  sampleButton!.setTitle("Sample \n UI Button", forState: .Normal)
  sampleButton!.titleLabel?.lineBreakMode = .ByWordWrapping
  sampleButton!.titleLabel?.textAlignment = .Center
  sampleButton!.setTitleColor(UIColor.whiteColor(), forState: .Normal)
  sampleButton!.layer.cornerRadius = 6
  sampleButton!.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.6)
  sampleButton?.tintColor =  UIColor.brownColor()


  //Add padding around text
  sampleButton!.titleEdgeInsets = UIEdgeInsetsMake(-10,-10,-10,-10)
  sampleButton!.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)

  //Action set up
  sampleButton!.addTarget(self, action: "sampleButtonClicked", forControlEvents: .TouchUpInside)
  self.view.addSubview(sampleButton!)


  //Button Constraints:
  sampleButton!.translatesAutoresizingMaskIntoConstraints = false

  //To anchor above the tab bar on the bottom of the screen:
  let bottomButtonConstraint = sampleButton!.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -20)

  //edge of the screen in InterfaceBuilder:
  let margins = view.layoutMarginsGuide
  let leadingButtonConstraint = sampleButton!.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)

  bottomButtonConstraint.active = true
  leadingButtonConstraint.active = true


 }
 func sampleButtonClicked(){

  print("sample Button Clicked")

 }

API没有改变——只有语法改变了。你可以创建一个UIButton并像这样添加它:

var button = UIButton(frame: CGRectMake(0, 0, 50, 50))
self.view.addSubview(button) // assuming you're in a view controller

Swift:以编程方式创建Ui按钮

let myButton = UIButton()

myButton.titleLabel!.frame = CGRectMake(15, 54, 300, 500)
myButton.titleLabel!.text = "Button Label"
myButton.titleLabel!.textColor = UIColor.redColor()
myButton.titleLabel!.textAlignment = .Center
self.view.addSubview(myButton)