2014-06-08 40 views
90

我正尝试以编程方式构建UI。我如何得到这个动作?我正在用Swift开发。在Swift中以编程方式制作UIButton

代码在viewDidLoad中:

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

回答

141

你只是缺少在选择名称末尾结肠。由于按下了一个参数,冒号必须在那里。另外你的按下的功能不应该嵌套在viewDidLoad内。

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(),而不要使用不赞成使用的文字字符串。

+0

当我按下按钮时,该应用程序仍然崩溃。 – Benr783

+0

对不起。该功能不应嵌套。 – Dash

+1

嘿,你能告诉我冒号后面的逻辑,我们需要在代表动作的字符串后添加吗? – juniorgarcia

10

是在模拟器中。有些时候,它不会识别选择器,它似乎有一个错误。即使我不面向你的代码,那么我只是改变了动作名称(选择器)。它的工作原理

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

您应该能够通过访问的UIButtontitleLabel属性通过创建一个自定义UI按钮。

Class Reference斯威夫特:关于titleLabel财产,它说,“虽然这个属性是只读的,它自己的属性是读/写,主要使用这些属性来配置按钮上的文字。”

斯威夫特,您可以直接修改titleLabel的性质类似这样的:

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) 

编辑

雨燕3.1语法

+1

我试着运行此代码,它不适合我。标题标签的chidlren似乎存在 – user2202911

1

斯威夫特: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 
0

在斯威夫特我们可以通过我们的viewcontroller.swift文件编写这些代码编程让一个按钮...

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

尝试these..i希望它可以帮助...

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 

} 

这些是单击按钮事件..

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

的UIButton与约束iOS 9.1/Xcode 7.1.1/Swift 2.1

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\nLocation", 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!") 
    } 

该按钮固定在标签栏上方的左下角。

+0

“ getCurrentLocation'帮助我们获得位置吗? – nyxee

+0

@nyxee,这里的问题是ab了解如何以编程方式制作按钮。获取用户的位置与制作按钮无关。要获得用户的位置,请参阅此处; https://developer.apple.com/reference/corelocation/cllocationmanager。如果你无法弄清楚,请问你自己的问题。 – 7stud

36

Swift 2.2 Xcode 7。3

由于Objective-C的字符串文字现在已弃用为按钮回调方法

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

夫特3的Xcode 8

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") 
} 
+0

@ n.by.n如何在这个方法buttonClicked()上传递参数? – ArgaPK

0

夫特:UI按钮创建编程,

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

对于Swift 3 Xcode中8 .......

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

斯威夫特3

//Create button 
      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) 

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

斯威夫特3:您可以创建一个UIButton编程

无论是内部的方法的范围,例如在ViewDidLoad() 要肯定要添加约束的按钮,否则你不会看到它

let button = UIButton() 
button.translatesAutoresizingMaskIntoConstraints = false 
button.target(forAction: #selector(buttonAction), withSender: self) 
//button.backgroundColor etc 

view.addSubview(button) 

func buttonAction() { 
    //some Action 
} 

或外部的范围为全局变量,从任何地方访问它在你的module

let button: UIButton = { 
    let b = UIButton() 
    b.translatesAutoresizingMaskIntoConstraints = false 
    //b.backgroundColor etc 
    return b 
}() 

,然后你设置的约束

func setupButtonView() { 
    view.addSubview(button) 
    button.widthAnchor.constraint(equalToConstant: 40).isActive = true 
    button.heightAnchor.constraint(equalToConstant: 40).isActive = true 
    // etc 

} 
0

在使用这种Objective-C的

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

在最新斯威夫特

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

斯威夫特4

private func createButton { 
     let sayButtonT = UIButton(type: .custom) 
     sayButtonT.addTarget(self, action: #selector(sayAction(_:)), for: .touchUpInside) 
    } 

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

    } 
1

雨燕 “按钮工厂” 扩展的UIButton使用这个(虽然我们是在它)也是的UILabel,像这样:

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 Ve中测试Swift rsion 9.2(9C40b)Swift 4.x

0

如果您进入主要故事板部分,并在右下角用圆角转到圆形并使用空白按钮。然后在代码中使用@IBAction来连接它。然后你可以用它来创建一个@IBAction函数。