First Swift Program

I wrote my first Swift program tonight. It simply puts a button on the screen and handles the click event. Everything is done in code. Code on Github: https://github.com/melling/swift/tree/master/CenteredAutoLayoutButton

The relevant functions are here:

 func addButton() {
        centeredButton = UIButton()
        centeredButton.setTitle("Am I centered?", forState: .Normal)
        centeredButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
        centeredButton.setTranslatesAutoresizingMaskIntoConstraints(false)
        centeredButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
        
        self.view.addSubview(centeredButton)
        
        var viewDictionary:Dictionary = ["centeredButton": centeredButton]
        
        let horizontal:[AnyObject]! = NSLayoutConstraint.constraintsWithVisualFormat("H:|-50-[centeredButton]-50-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewDictionary)
        
        let vertical:[AnyObject]! = NSLayoutConstraint.constraintsWithVisualFormat("V:|-100-[centeredButton]-100-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewDictionary)
        self.view.addConstraints(horizontal)
        self.view.addConstraints(vertical)
        
    }
    
    func pressed(sender: UIButton!) {
        var alertView = UIAlertView();
        alertView.addButtonWithTitle("Ok");
        alertView.title = "My Title";
        alertView.message = "Congratulations";
        alertView.show();
    }

Advertisements