如何以编程方式创建按钮?

val*_*lek 250 uibutton ios swift

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

Ani*_*ese 405

以下是UIButton使用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")
}
Run Code Online (Sandbox Code Playgroud)

使用NSLayoutConstraint而不是frame为每个iPhone屏幕正确放置按钮可能更好.

更新了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")
}
Run Code Online (Sandbox Code Playgroud)

更新了Swift 4.2的代码:

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)
}

@objc func buttonAction(sender: UIButton!) {
  print("Button tapped")
}
Run Code Online (Sandbox Code Playgroud)

如果func buttonAction声明private或上述仍然有效internal.

  • 并且不要忘记你的行动的功能不能是私人的 (6认同)
  • 并且不要忘记您的目标类应该从NSObject派生 (3认同)
  • 从Swift 1.2开始,不能再使用"as"进行向下转换,它们必须"强制转换"为"as!". (3认同)
  • 很奇怪他们决定用字符串而不是使用函数来执行操作(使用字符串它比选择器更不安全!).向后兼容Obj-C可能:( (2认同)

Akh*_*tar 99

您可以通过这种方式以编程方式添加UIButton,UIlable和UITextfield.

UIButton代码

// var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
let button = UIButton(type: .System) // let preferred over var here
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
Run Code Online (Sandbox Code Playgroud)

UILabel代码

var label: UILabel = UILabel()
label.frame = CGRectMake(50, 50, 200, 21)
label.backgroundColor = UIColor.blackColor()
label.textColor = UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Center
label.text = "test label"
self.view.addSubview(label)
Run Code Online (Sandbox Code Playgroud)

UITextField代码

var txtField: UITextField = UITextField()
txtField.frame = CGRectMake(50, 70, 200, 30)
txtField.backgroundColor = UIColor.grayColor()
self.view.addSubview(txtField)
Run Code Online (Sandbox Code Playgroud)

希望这对你有所帮助.


Mus*_*ari 59

对于Swift 3

let button = UIButton()
button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
button.backgroundColor = UIColor.red
button.setTitle("your Button Name", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)

func buttonAction(sender: UIButton!) {
    print("Button tapped")
}
Run Code Online (Sandbox Code Playgroud)

对于Swift 4

 let button = UIButton()
 button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
 button.backgroundColor = UIColor.red
 button.setTitle("Name your Button ", for: .normal)
 button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
 self.view.addSubview(button)

 @objc func buttonAction(sender: UIButton!) {
    print("Button tapped")
 }
Run Code Online (Sandbox Code Playgroud)

  • 在Swift 4之前,"func"需要添加"@objc". (2认同)

use*_*143 29

斯威夫特3

let btn = UIButton(type: .custom) as UIButton
btn.backgroundColor = .blue
btn.setTitle("Button", for: .normal)
btn.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
self.view.addSubview(btn)

func clickMe(sender:UIButton!) {
  print("Button Clicked")
}
Run Code Online (Sandbox Code Playgroud)

产量

在此输入图像描述


Cod*_*der 17

如何使用Swift 3.0做到这一点.

func createButton() {
    let button = UIButton(type: .system)
    button.frame = CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0)
    button.setTitle(NSLocalizedString("Button", comment: "Button"), for: .normal)
    button.backgroundColor = .green
    button.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
    view.addSubview(button)
}

@objc func buttonAction(sender: UIButton) {
    print("Button pushed")
}
Run Code Online (Sandbox Code Playgroud)


A.G*_*A.G 16

 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")

 }
Run Code Online (Sandbox Code Playgroud)


Cez*_*cik 14

API没有改变 - 只有语法有.您可以UIButton像这样添加并添加:

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


Zgp*_*ace 11

对于 Swift 5 和 Swift 4 一样

 let button = UIButton()
 button.frame = CGRect(x: self.view.frame.size.width - 60, y: 60, width: 50, height: 50)
 button.backgroundColor = UIColor.red
 button.setTitle("Name your Button ", for: .normal)
 button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
 self.view.addSubview(button)

 @objc func buttonAction(sender: UIButton!) {
    print("Button tapped")
 }
Run Code Online (Sandbox Code Playgroud)


Dha*_*ngh 7

您可以像这样创建,也可以像这样添加动作....

import UIKit

let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))

init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
{       super.init(nibName: nibName, bundle: nibBundle) 
        myButton.targetForAction("tappedButton:", withSender: self)
}

func tappedButton(sender: UIButton!)
{ 
     println("tapped button")
}
Run Code Online (Sandbox Code Playgroud)


小智 6

在viewDidLoad
//添加Button中添加此代码

            var button=UIButton(frame: CGRectMake(150, 240, 75, 30))
            button.setTitle("Next", forState: UIControlState.Normal)
            button.addTarget(self, action: "buttonTapAction:", forControlEvents: UIControlEvents.TouchUpInside)
            button.backgroundColor = UIColor.greenColor()
            self.view.addSubview(button)
Run Code Online (Sandbox Code Playgroud)

将此功能写在外面,当您点击按钮时会调用此功能

func buttonTapAction(sender:UIButton!)
{
    println("Button is working")
}
Run Code Online (Sandbox Code Playgroud)


Muh*_*sim 6

在Swift 2和iOS 9.2.1中

var button: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
self.button.frame = CGRectMake(130, 70, 60, 20)
self.button.setTitle("custom button", forState: UIControlState.Normal)
self.button.addTarget(self, action:"buttonActionFuncName", forControlEvents: UIControlEvents.TouchUpInside)
self.button.setTitleColor(UIColor.blackColor(), forState: .Normal)
self.button.layer.borderColor = UIColor.blackColor().CGColor
self.button.titleLabel?.font = UIFont(name: "Helvetica-Bold", size: 13)
self.view.addSubview(self.button)
Run Code Online (Sandbox Code Playgroud)


Con*_*nor 4

有可能的。除了使用 swift 语法之外,您所做的一切几乎都以相同的方式进行。例如,您可以在如下代码中创建一个 UIButton:

 var button: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 100))
Run Code Online (Sandbox Code Playgroud)