How do you use Interface builder with Swift?

后端 未结 5 1593
日久生厌
日久生厌 2021-02-07 12:11

When hooking Swift code up to a Storyboard, how do you add the IBAction and IBOutlet tags?

相关标签:
5条回答
  • 2021-02-07 12:38

    Below code shows IBOutlet and IBAction format in Swift :

    class MyViewController: UIViewController {
    
      @IBOutlet weak var btnSomeButton: UIButton?
      @IBOutlet weak var lblLabelItem: UILabel?
    
      @IBAction func btnSomeButtonClicked(sender: UIButton) {
        ...
      }
    }
    

    You can bind them same way as done in Objective-C.

    0 讨论(0)
  • 2021-02-07 12:41

    While creating a project, you should have selected the storyboard, so that you can add your IBOutlet's directly in the story board.

    The Below code gives you a idea of how to add IBOutlet to the UILabel

    class ViewController: UIViewController {
    
        @IBOutlet var label : UILabel
    
    }
    
    0 讨论(0)
  • 2021-02-07 12:44

    Just use old ctrl + drag technique which was popular in Xcode5 and everything works fine.

    0 讨论(0)
  • 2021-02-07 12:46

    I would agree more with Jayprakash than the upvoted first answer. The only thing I would correct is the marking of the IBOutlets as implicitly unwrapped with the ! The first answer used to be correct, but several changes were made in Swift and how it interacts with IB in the latest release. In Swift, IBOutlets no longer have any implicit behavior or magic--they are simply annotations for IB. As of the date of this response, the following code is correct:

    // How to specify an the equivalent of IBOutletCollection in Swift
    @IBOutlet var fields: [UITextField]!
    // How to specify a standard IBOutlet
    @IBOutlet weak var button: UIButton!
    // How to specify an IBAction
    @IBAction func buttonWasPressed(sender: UIButton) { ... } 
    
    0 讨论(0)
  • 2021-02-07 12:47

    Add IBAction and IBOutlet attributes to variables and functions so they can be visible in Interface builder.

    class ViewController: UIViewController {
    
        @IBOutlet var label: UILabel?
    
        @IBAction func doTap(x:UIButton) {
            println("Tapped: \(x)")
        }
    }
    
    0 讨论(0)
提交回复
热议问题