【问题标题】:How to create a button programmatically?如何以编程方式创建按钮?
【发布时间】:2023-03-25 07:35:02
【问题描述】:

如何在 Swift 中以编程方式创建图形元素(如 UIButton)?我尝试创建按钮并将其添加到视图中,但未能成功。

【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

    这是使用 targetAction 以编程方式添加 UIButton 的完整解决方案。
    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 屏幕的按钮。

    将代码更新到 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")
    }
    

    将代码更新到 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")
    }
    

    如果func buttonAction 被声明为privateinternal,上述方法仍然有效。

    【讨论】:

    • 别忘了你的目标类应该派生自 NSObject
    • 别忘了你操作的函数不能是私有的
    • 奇怪的是,他们决定用字符串而不是函数来执行操作(字符串比选择器更不安全!)。可能与 Obj-C 向后兼容 :(
    • 从 Swift 1.2 开始,向下转换不能再用“as”完成,它们必须用“as!”“强制失败”。
    • 有人知道在创建空应用程序时在哪里复制粘贴代码吗?
    【解决方案2】:

    您可以通过这种方式以编程方式添加 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)
    

    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)
    

    UITextField 代码

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

    希望这对你有帮助。

    【讨论】:

    • 那么,为什么你在 UIButton 之前分享的第一行代码中需要“as”运算符...?
    • buttonWithType 返回类型 AnyObject,所以需要将其转换为 UIButton
    • @ElgsQianChen 您可以根据需要使用此代码。例如,您想在视图出现时添加一个 UIButton,您可以在 viewWillAppear 中添加代码。
    • 从 Swift 1.2 开始,向下转换不能再用“as”完成,它们必须用“as!”“强制失败”。
    • 对于遇到Objective C String literals deprecated warnings的人正确答案在这里:stackoverflow.com/a/36308587/968848
    【解决方案3】:

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

    适用于 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")
     }
    

    【讨论】:

    • button.frame = (frame: CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)) 应该是button.frame = CGRect(x: self.view.frame.size.width - 60, y: 20, width: 50, height: 50)
    • 在 Swift 4 中“func”前需要添加“@objc”。
    【解决方案4】:

    斯威夫特 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")
    }
    

    输出

    【讨论】:

    • 谢谢,m8!今天开始使用 Swift,所以一切都有些奇怪(:
    【解决方案5】:

    如何使用 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")
    }
    

    【讨论】:

      【解决方案6】:
       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")
      
       }
      

      【讨论】:

        【解决方案7】:

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

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

        【讨论】:

          【解决方案8】:

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

          【讨论】:

            【解决方案9】:

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

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

            【讨论】:

            • 抱歉,编译器在一行中发送了错误 - self.view.addSubview(view: myButton)。错误是下一个:“调用中的外部参数标签'view:'”
            • 请删除此行 self.view.addSubview(view: myButton) 有关更多信息,请参阅我编辑的答案。
            • 谢谢,但是如何在 self.view 上添加这个按钮?
            【解决方案10】:

            在 viewDidLoad 中添加此代码
            //添加按钮

                        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)
            

            在外面写这个函数,当你点击按钮时会调用这个函数

            func buttonTapAction(sender:UIButton!)
            {
                println("Button is working")
            }
            

            【讨论】:

              【解决方案11】:

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

              【讨论】:

                【解决方案12】:

                这是可能的。除了使用 swift 语法外,你做的一切几乎都是一样的。例如,您可以在如下代码中创建一个 UIButton:

                 var button: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 100))
                

                【讨论】:

                  【解决方案13】:

                  从情节提要创建 UIButton: 1 - 将 UIButton 对象从对象库拖到情节提要文件中的 ViewController 2 - 显示助理编辑器 3 - 右键单击​​从上面创建的 UIButton 拖动到您的类中。结果如下:

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

                  以编程方式创建 UIButton: 1-写入“覆盖函数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")
                  }
                  

                  【讨论】:

                  • 从 Swift 1.2 开始,向下转换不能再用“as”完成,它们必须用“as!”“强制失败”。
                  【解决方案14】:
                              let myFirstButton = UIButton()
                              myFirstButton.setTitle("Software Button", forState: .Normal)
                              myFirstButton.setTitleColor(UIColor.redColor(), forState: .Normal)
                              myFirstButton.frame = CGRectMake(100, 300, 150, 50)
                              myFirstButton.backgroundColor = UIColor.purpleColor()
                              myFirstButton.layer.cornerRadius = 14
                              myFirstButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
                              self.view.addSubview(myFirstButton)
                              myFirstButton.hidden=true
                              nameText.delegate = self
                  
                  
                  func pressed(sender: UIButton!) {
                          var alertView = UIAlertView()
                          alertView.addButtonWithTitle("Ok")
                          alertView.title = "title"
                          alertView.message = "message"
                          alertView.show();
                      }
                  

                  【讨论】:

                    【解决方案15】:

                    是的,在模拟器中。有时它不会识别选择器,似乎存在错误。即使我没有遇到您的代码,我也只是更改了操作名称(选择器)。有效

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

                    【讨论】:

                    • 好像我遇到了同样的问题。我最初在情节提要中创建了一个 IBAction 按钮,但我得到“无法识别的选择器已发送到实例”,然后我删除了以这种方式创建的 IBAction 并尝试使用 .addTarget,它们都导致相同的错误。
                    • 对我有用的是删除 .swift 文件中的所有 IBOutlet 和 IBAction 代码以及 InterfaceBuilder 中的所有连接。然后重新创建一切。
                    【解决方案16】:

                    第 1 步:创建一个新项目

                    第 2 步:在 ViewController.swift 中

                    import UIKit
                    
                    class ViewController: UIViewController {
                    
                        override func viewDidLoad() {
                            super.viewDidLoad()
                    
                            // CODE
                            let btn = UIButton(type: UIButtonType.System) as UIButton        
                            btn.backgroundColor = UIColor.blueColor()
                            btn.setTitle("CALL TPT AGENT", forState: UIControlState.Normal)
                            btn.frame = CGRectMake(100, 100, 200, 100)
                            btn.addTarget(self, action: "clickMe:", forControlEvents: UIControlEvents.TouchUpInside)
                            self.view.addSubview(btn)
                    
                        }
                    
                        func clickMe(sender:UIButton!) {
                          print("CALL")
                        }
                    
                        override func didReceiveMemoryWarning() {
                            super.didReceiveMemoryWarning()
                            // Dispose of any resources that can be recreated.
                        }
                    
                    
                    }
                    

                    【讨论】:

                      【解决方案17】:

                      这对我很有效,#DynamicButtonEvent #IOS #Swift #Xcode

                      func setupButtonMap(){
                          let mapButton = UIButton(type: .system)
                          mapButton.setImage(#imageLiteral(resourceName: "CreateTrip").withRenderingMode(.alwaysOriginal), for: .normal)
                          mapButton.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
                          mapButton.contentMode = .scaleAspectFit
                          mapButton.backgroundColor = UIColor.clear
                          mapButton.addTarget(self, action: #selector(ViewController.btnOpenMap(_:)), for: .touchUpInside)
                          navigationItem.leftBarButtonItem = UIBarButtonItem(customView: mapButton)
                          }
                      @IBAction func btnOpenMap(_ sender: Any?) {
                          print("Successful")
                      }
                      

                      【讨论】:

                        【解决方案18】:

                        在 Swift 4.2 中编写此示例代码,以编程方式添加按钮。

                        override func viewDidLoad() {
                            super.viewDidLoad()
                                let myButton = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
                                myButton.backgroundColor = .green
                                myButton.setTitle("Hello UIButton", for: .normal)
                                myButton.addTarget(self, action: #selector(myButtonAction), for: .touchUpInside)
                                self.view.addSubview(myButton)
                        }
                        
                         @objc func myButtonAction(sender: UIButton!) {
                            print("My Button tapped")
                        }
                        

                        【讨论】:

                          【解决方案19】:
                              // UILabel:
                              let label = UILabel()
                              label.frame = CGRectMake(35, 100, 250, 30)
                              label.textColor = UIColor.blackColor()
                              label.textAlignment = NSTextAlignment.Center
                              label.text = "Hello World"
                              self.view.addSubview(label)
                          
                              // UIButton:
                              let btn: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
                              btn.frame = CGRectMake(130, 70, 60, 20)
                              btn.setTitle("Click", forState: UIControlState.Normal)
                              btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
                              btn.addTarget(self, action:Selector("clickAction"), forControlEvents: UIControlEvents.TouchUpInside)
                              view.addSubview(btn)
                          
                          
                              // Button Action:
                              @IBAction func clickAction(sender:AnyObject)
                              {
                                  print("Click Action")
                              }
                          

                          【讨论】:

                            【解决方案20】:

                            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)
                            

                            【讨论】:

                              【解决方案21】:

                               func viewDidLoad(){
                                                  saveActionButton = UIButton(frame: CGRect(x: self.view.frame.size.width - 60, y: 0, width: 50, height: 50))
                                                  self.saveActionButton.backgroundColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 0.7)
                                                  saveActionButton.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
                                                  self.saveActionButton.setTitle("Done", for: .normal)
                                                  self.saveActionButton.layer.cornerRadius = self.saveActionButton.frame.size.width / 2
                                                  self.saveActionButton.layer.borderColor = UIColor.darkGray.cgColor
                                                  self.saveActionButton.layer.borderWidth = 1
                                                  self.saveActionButton.center.y = self.view.frame.size.height - 80
                                                  self.view.addSubview(saveActionButton)
                                      }
                              
                                        func doneAction(){
                                        print("Write your own logic")
                                       }
                              

                              【讨论】:

                                【解决方案22】:

                                我通常会去设置 UIBotton 的扩展。斯威夫特 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) 
                                        }
                                    }
                                

                                【讨论】:

                                  【解决方案23】:
                                  Uilabel code 
                                  
                                  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)
                                  

                                  【讨论】:

                                  • 始终建议在您的代码中添加一些解释
                                  【解决方案24】:
                                  override func viewDidLoad() {
                                  
                                  super.viewDidLoad()
                                      // Do any additional setup after loading the view, typically from a nib.
                                  
                                      var imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150));
                                      var image = UIImage(named: "BattleMapSplashScreen.png");
                                      imageView.image = image;
                                      self.view.addSubview(imageView);
                                  
                                  }
                                  

                                  【讨论】:

                                    猜你喜欢
                                    • 2018-06-14
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    相关资源
                                    最近更新 更多