C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Connect: Please click Connect. An IBOutlet field with name "numberButton" and type UIButton will appear in ViewController.swift.
Example UIButton: Swift
//
// ViewController.swift
// ExampleTime6
//
// ...
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet weak var numberButton: UIButton!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
And: Click on the circle and rag it also to your ViewController.swift file. We need to connect an action.
Here: The actionTriggered func appears in our ViewController.swift file. In it we will add some Swift statements.
Example IBAction func: Swift
//
// ViewController.swift
// ExampleTime6
//
// ...
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func actionTriggered(sender: AnyObject) {
}
@IBOutlet weak var numberButton: UIButton!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
CurrentTitle: This is an optional string. We use an "if let" statement to access its value safely.
Int: We parse the Button's title as an integer with the Int func. We check the optional result in an if-let statement.
SetTitle: We call setTitle with the string returned by the String func. We use UIControlState.Normal for the forState argument.
Example currentTitle, setTitle use: Swift
//
// ViewController.swift
// ExampleTime6
//
// ...
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func actionTriggered(sender: AnyObject) {
// This runs when the button is tapped.
// ... Get title of Button.
if let title = numberButton.currentTitle {
// Parse title as Int.
if let number = Int(title) {
// Change the title by adding 1000.
let newNumber = number + 1000
let newString = String(newNumber)
// Set a new title for the Button.
numberButton.setTitle(newString,
forState: UIControlState.Normal)
}
}
}
@IBOutlet weak var numberButton: UIButton!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}