关于ios:在Swift中以编程方式创建UIButton

Make a UIButton programmatically in Swift

我正在尝试以编程方式构建UI。如何使此操作有效?我正在和斯威夫特一起发展。

VIEWDIDLOAD中的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let myFirstLabel = UILabel()
        let myFirstButton = UIButton()
        myFirstLabel.text ="I made a label on the screen #toogood4you"
        myFirstLabel.font = UIFont(name:"MarkerFelt-Thin", size: 45)
        myFirstLabel.textColor = UIColor.redColor()
        myFirstLabel.textAlignment = .Center
        myFirstLabel.numberOfLines = 5
        myFirstLabel.frame = CGRectMake(15, 54, 300, 500)
        myFirstButton.setTitle("?", forState: .Normal)
        myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
        myFirstButton.frame = CGRectMake(15, -50, 300, 500)
        myFirstButton.addTarget(self, action:"pressed", forControlEvents: .TouchUpInside)
        self.view.addSubview(myFirstLabel)
        self.view.addSubview(myFirstButton)
    }

        func pressed(sender: UIButton!) {
            var alertView = UIAlertView();
            alertView.addButtonWithTitle("Ok");
            alertView.title ="title";
            alertView.message ="message";
            alertView.show();
        }

您只是在选择器名称的末尾缺少冒号。因为pressed接受一个参数,所以冒号必须在那里。另外,您按下的函数不应该嵌套在viewdidload中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let myFirstLabel = UILabel()
    let myFirstButton = UIButton()
    myFirstLabel.text ="I made a label on the screen #toogood4you"
    myFirstLabel.font = UIFont(name:"MarkerFelt-Thin", size: 45)
    myFirstLabel.textColor = UIColor.redColor()
    myFirstLabel.textAlignment = .Center
    myFirstLabel.numberOfLines = 5
    myFirstLabel.frame = CGRectMake(15, 54, 300, 500)
    myFirstButton.setTitle("?", forState: .Normal)
    myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
    myFirstButton.frame = CGRectMake(15, -50, 300, 500)
    myFirstButton.addTarget(self, action: #selector(myClass.pressed(_:)), forControlEvents: .TouchUpInside)
    self.view.addSubview(myFirstLabel)
    self.view.addSubview(myFirstButton)
}

@objc func pressed(sender: UIButton!) {
    var alertView = UIAlertView()
    alertView.addButtonWithTitle("Ok")
    alertView.title ="title"
    alertView.message ="message"
    alertView.show()
}

编辑:更新以反映SWIFT 2.2中的最佳实践。#应使用selector(),而不是不推荐使用的文本字符串。


Swift 2.2代码7.3

因为对于按钮回调方法,现在不推荐使用objective-c字符串

1
2
3
4
5
6
7
8
9
let button:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
button.backgroundColor = UIColor.blackColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(self, action:#selector(self.buttonClicked), forControlEvents: .TouchUpInside)
self.view.addSubview(button)

func buttonClicked() {
     print("Button Clicked")
}

SWIFT 3 XCODE 8

1
2
3
4
5
6
7
8
9
let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
button.backgroundColor = .black
button.setTitle("Button", for: .normal)
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

func buttonClicked() {
    print("Button Clicked")
}

SWIFT 4 XCODE 9

1
2
3
4
5
6
7
8
9
let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
button.backgroundColor = .black
button.setTitle("Button", for: .normal)
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

@objc func buttonClicked() {
    print("Button Clicked")
}


斯威夫特4

1
2
3
4
5
6
7
8
    private func createButton {
        let sayButtonT = UIButton(type: .custom)
        sayButtonT.addTarget(self, action: #selector(sayAction(_:)), for: .touchUpInside)
    }

    @objc private func sayAction(_ sender: UIButton?) {

    }

是的,在模拟器里。有时它无法识别选择器,似乎有一个错误。即使我面对的不是你的代码,我只是改变了操作名(选择器)。它工作

1
2
3
4
5
6
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)

这里有一个选择器函数示例:

1
2
3
4
5
6
func buttonAction(sender:UIButton!) {
    var btnsendtag:UIButton = sender
    if btnsendtag.tag == 22 {            
        //println("Button tapped tag 22")
    }
}

斯威夫特3/4

//创建按钮

1
2
3
4
5
6
7
8
9
10
11
12
let button = UIButton(frame: CGRect(x: 20, y: 20, width: 200, height: 60))
 button.setTitle("Email", for: .normal)
 button.backgroundColor = .white
 button.setTitleColor(UIColor.black, for: .normal)
 button.addTarget(self, action: #selector(self.buttonTapped), for: .touchUpInside)
 myView.addSubview(button)



@objc func buttonTapped(sender : UIButton) {
                //Write button action here
            }

您应该能够通过访问ui button的titleLabel属性以编程方式创建自定义的ui按钮。

swift中的每个类引用:关于titleLabel属性,它说"尽管这个属性是只读的,但它自己的属性是读/写的。主要使用这些属性配置按钮的文本。"

在Swift中,可以直接修改标题标签的属性,如下所示:

1
2
3
4
5
6
7
let myFirstButton = UIButton()
myFirstButton.titleLabel!.text ="I made a label on the screen #toogood4you"
myFirstButton.titleLabel!.font = UIFont(name:"MarkerFelt-Thin", size: 45)
myFirstButton.titleLabel!.textColor = UIColor.red
myFirstButton.titleLabel!.textAlignment = .center
myFirstButton.titleLabel!.numberOfLines = 5
myFirstButton.titleLabel!.frame = CGRect(x: 15, y: 54, width: 300, height: 500)

编辑

Swift 3.1语法


试试这些……我希望能有帮助……

1
2
3
4
5
6
7
8
9
10
11
12
13
override func viewDidLoad() {
super.viewDidLoad()  

    let btn = UIButton()
    btn.frame = CGRectMake(10, 10, 50, 50)  //set frame
    btn.setTitle("btn", forState: .Normal)  //set button title
    btn.setTitleColor(UIColor.redColor(), forState: .Normal) //set button title color
    btn.backgroundColor = UIColor.greenColor() //set button background color
    btn.tag = 1 // set button tag
    btn.addTarget(self, action:"btnclicked:", forControlEvents: .TouchUpInside) //add button action
    self.view.addSubview(btn) //add button in view

}

这些是按钮单击事件。

1
2
3
4
func btnclicked(sender: UIButton!)
{
    //write the task you want to perform on buttons click event..
}

Swift 3:您可以通过编程方式创建一个UIButton

在方法范围内,例如在ViewDidLoad()中请确保向按钮添加约束,否则您将看不到它。

1
2
3
4
5
6
7
8
9
10
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.target(forAction: #selector(buttonAction), withSender: self)
//button.backgroundColor etc

view.addSubview(button)

func buttonAction() {
   //some Action
}

或者作为全局变量从您的module中的任何位置访问它。

1
2
3
4
5
6
let button: UIButton = {
   let b = UIButton()
   b.translatesAutoresizingMaskIntoConstraints = false
   //b.backgroundColor etc
   return b
}()

然后设置约束

1
2
3
4
5
6
7
func setupButtonView() {
   view.addSubview(button)
   button.widthAnchor.constraint(equalToConstant: 40).isActive = true
   button.heightAnchor.constraint(equalToConstant: 40).isActive = true
   // etc

}

swift:ui按钮以编程方式创建,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var button: UIButton = UIButton(type: .Custom)

button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0)

button.addTarget(self, action: #selector(self.aMethod), forControlEvents: .TouchUpInside)

button.tag=2

button.setTitle("Hallo World", forState: .Normal)

view.addSubview(button)


func aMethod(sender: AnyObject) {
    print("you clicked on button \(sender.tag)")
}

uibutton的swift"button factory"扩展名(以及我们在那里的时候)也适用于uilabel,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
extension UILabel
{
// A simple UILabel factory function
// returns instance of itself configured with the given parameters

// use example (in a UIView or any other class that inherits from UIView):

//   addSubview(   UILabel().make(     x: 0, y: 0, w: 100, h: 30,
//                                   txt:"Hello World!",
//                                 align: .center,
//                                   fnt: aUIFont,
//                              fntColor: UIColor.red)                 )
//

func make(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat,
          txt: String,
          align: NSTextAlignment,
          fnt: UIFont,
          fntColor: UIColor)-> UILabel
{
    frame = CGRect(x: x, y: y, width: w, height: h)
    adjustsFontSizeToFitWidth = true
    textAlignment = align
    text = txt
    textColor = fntColor
    font = fnt
    return self
}
// Of course, you can make more advanced factory functions etc.
// Also one could subclass UILabel, but this seems to be a     convenient case for an extension.
}


extension UIButton
{
// UIButton factory returns instance of UIButton
//usage example:

// addSubview(UIButton().make(x: btnx, y:100, w: btnw, h: btnh,
// title:"play", backColor: .red,
// target: self,
// touchDown: #selector(play), touchUp: #selector(stopPlay)))


func make(   x: CGFloat,y: CGFloat,
             w: CGFloat,h: CGFloat,
                  title: String, backColor: UIColor,
                  target: UIView,
                  touchDown:  Selector,
                  touchUp:    Selector ) -> UIButton
{
    frame = CGRect(x: x, y: y, width: w, height: h)
    backgroundColor = backColor
    setTitle(title, for: .normal)
    addTarget(target, action: touchDown, for: .touchDown)
    addTarget(target, action: touchUp  , for: .touchUpInside)
    addTarget(target, action: touchUp  , for: .touchUpOutside)

    return self
}
}

在Xcode版本9.2(9c40b)的swift中测试swift 4.x


swift:ui按钮以编程方式创建

1
2
3
4
5
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


对于Swift 3 Xcode 8……

1
2
3
4
5
6
7
let button = UIButton(frame: CGRect(x: 0, y: 0, width: container.width, height: container.height))
        button.addTarget(self, action: #selector(self.barItemTapped), for: .touchUpInside)


func barItemTapped(sender : UIButton) {
    //Write button action here
}

Swift 4.2-Xcode 10.1

使用闭包

1
2
3
4
5
6
let button: UIButton = {
  let button = UIButton(type: .system)
  button.titleLabel?.font = UIFont.systemFont(ofSize: 20)
  ...
  return button
}()

Using this in Objective-C

1
2
3
4
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[testButton setTitle:@"Go to here" forState:UIControlStateNormal];
testButton.frame = CGRectMake(20, 20, 150, 150);    
[self.view addSubview:testButton];

Using this in Latest Swift

1
2
3
4
5
let testButton   = UIButton(type: UIButtonType.system) as UIButton
testButton.frame = CGRectMake(160, 160, 80, 20)
testButton.backgroundColor = UIColor.green
testButton.setTitle("Button testing:-", forState: UIControlState.normal)
self.view.addSubview(testButton)

iOS 9.1/Xcode 7.1.1/Swift 2.1中有约束的uibutton:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import UIKit
import MapKit

class MapViewController: UIViewController {  

    override func loadView() {
        mapView = MKMapView()  //Create a view...
        view = mapView         //assign it to the ViewController's (inherited) view property.
                               //Equivalent to self.view = mapView

        myButton = UIButton(type: .RoundedRect)  //RoundedRect is an alias for System (tested by printing out their rawValue's)
        //myButton.frame = CGRect(x:50, y:500, width:70, height:50)  //Doesn't seem to be necessary when using constraints.
        myButton.setTitle("Current
Location", forState: .Normal)
        myButton.titleLabel?.lineBreakMode = .ByWordWrapping  //If newline in title, split title onto multiple lines
        myButton.titleLabel?.textAlignment = .Center
        myButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        myButton.layer.cornerRadius = 6   //For some reason, a button with type RoundedRect has square corners
        myButton.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5) //Make the color partially transparent
        //Attempt to add padding around text. Shrunk the frame when I tried it.  Negative values had no effect.
        //myButton.titleEdgeInsets = UIEdgeInsetsMake(-10,-10,-10,-10)
        myButton.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)  //Add padding around text.

        myButton.addTarget(self, action:"getCurrentLocation:", forControlEvents: .TouchUpInside)
        mapView.addSubview(myButton)

        //Button Constraints:
        myButton.translatesAutoresizingMaskIntoConstraints = false //***
        //bottomLayoutGuide(for tab bar) and topLayoutGuide(for status bar) are properties of the ViewController
        //To anchor above the tab bar on the bottom of the screen:
        let bottomButtonConstraint = myButton.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -20) //Implied call of self.bottomLayoutGuide. Anchor 20 points **above** the top of the tab bar.
        //To anchor to the blue guide line that is inset from the left
        //edge of the screen in InterfaceBuilder:
        let margins = view.layoutMarginsGuide  //Now the guide is a property of the View.
        let leadingButtonConstraint = myButton.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)

        bottomButtonConstraint.active = true
        leadingButtonConstraint.active = true
    }


    func getCurrentLocation(sender: UIButton) {
        print("Current Location button clicked!")
    }

该按钮固定在左下角的选项卡栏上方。


在swift中,我们可以通过在viewcontroller.swift文件中编写此代码以编程方式生成按钮…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import UIKit

class ViewController: UIViewController
{  
private let firstbutton:UIButton = UIButton()

override func viewDidLoad() {
    super.viewDidLoad()
    self.firstbutton = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton
    self.firstbutton!.frame = CGRectMake(100, 200, 100, 100)
    self.firstbutton!.backgroundColor = UIColor.redColor()
    self.firstbutton!.setTitle("My Button", forState: UIControlState.Normal)
    self.firstbutton!.addTarget(self, action:#selector(self.firstButtonClicked), forControlEvents: .TouchUpInside)
    self.view.addSubview(firstbutton!)
    }

func firstButtonClicked(){
   print("First Button Clicked")
}


如果你进入故事板的主体部分,在右下角,用一个正方形进入圆圈,然后使用一个空白按钮。然后在代码中使用@ibaction将其连接起来。然后您可以用它生成一个@ibaction函数。


在iOS 12中,Swift 4.2和Xcode 10.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//For system type button
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 250, width: 100, height: 50)
//        button.backgroundColor = .blue
button.setTitle("Button", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13.0)
button.titleLabel?.textAlignment = .center//Text alighment center
button.titleLabel?.numberOfLines = 0//To display multiple lines in UIButton
button.titleLabel?.lineBreakMode = .byWordWrapping//By word wrapping
button.tag = 1//To assign tag value
button.btnProperties()//Call UIButton properties from extension function
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

//For custom type button (add image to your button)
let button2 = UIButton(type: .custom)
button2.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
//        button2.backgroundColor = .blue
button2.setImage(UIImage.init(named:"img.png"), for: .normal)
button2.tag = 2
button2.btnProperties()//Call UIButton properties from extension function
button2.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button2)

@objc func buttonClicked(sender:UIButton) {
    print("Button \(sender.tag) clicked")
}

//You can add UIButton properties like this also
extension UIButton {
    func btnProperties() {
        layer.cornerRadius = 10//Set button corner radious
        clipsToBounds = true
        backgroundColor = .blue//Set background colour
        //titleLabel?.textAlignment = .center//add properties like this
    }
}