user5698313
user5698313

Reputation:

Getting to grip with the high level ways of Xcode + Swift

Recently, I have started to study Swift with story board, Xcode, etc. I am struggling to understand the principals of ViewController code, as it seems to miss a lot of essentials - presumably to try and make things more simple - but it just isn't for programmers who have come from else where.

import UIKit

class ViewController: UIViewController {

    //Properties

    @IBOutlet weak var textFieldName: UITextField!
    @IBOutlet weak var submit: UIButton!
    @IBOutlet weak var submit1: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    //Actions

    @IBAction func onSubmit(sender: UIButton) {
        switch(sender){
            case submit:
                print("only 1");
            case submit1:
                print("222");
            default:
                print("nothing");
        }

    }
}

After following a basic tutorial, I have tried playing around on my own to test out my understanding. The IBOutlets, which define elements of the storyboard requires me to actually drag and drop it into the code in order for it to correctly correspond to the element. When I just type

@IBOutlet weak var submit1: UIButton!

Without having dragged it from storyboard - it does not work / correspond. So essentially there is more backend that I do not have control over?

Also, Actions. How come it prints without the method being called?! I must be missing something obvious - something to do with the attributes?

I want to be able to code things myself, and identify elements/buttons/etc myself without dragging and dropping, and not seeing the associations - submit1 and submit, at the moment, are set to the exact same thing: UIButton!

I am aware and accept my confusion and interpretation is clearly flawed and wrong. But could someone shed some light on the lower level activities of ViewController?

Thanks.

Upvotes: 1

Views: 61

Answers (1)

Lu_
Lu_

Reputation: 2685

If you don't want to drag and drop you can write, i don't see where is the problem

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)

Upvotes: 1

Related Questions