Created
November 23, 2022 12:44
-
-
Save vesic/e96c2ccb2859d100309e86f38915c150 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class ViewController: UIViewController { | |
var count: Int = 0 { | |
didSet { | |
countLabel.text = "\(count)" | |
} | |
} | |
let plusButton: UIButton = { | |
let button = UIButton() | |
button.setTitle("+", for: .normal) | |
button.setTitleColor(.systemBlue, for: .normal) | |
button.titleLabel?.font = UIFont.systemFont(ofSize: 120) | |
button.tag = 1 | |
return button | |
}() | |
let minusButton: UIButton = { | |
let button = UIButton() | |
button.setTitle("-", for: .normal) | |
button.setTitleColor(.systemBlue, for: .normal) | |
button.titleLabel?.font = UIFont.systemFont(ofSize: 120) | |
button.tag = 2 | |
return button | |
}() | |
let countLabel: UILabel = { | |
let label = UILabel() | |
label.text = "0" | |
label.textColor = .black | |
label.font = UIFont.systemFont(ofSize: 120) | |
return label | |
}() | |
let mainStack: UIStackView = { | |
let stack = UIStackView() | |
stack.axis = .vertical | |
stack.alignment = .center | |
return stack | |
}() | |
let buttonStack: UIStackView = { | |
let stack = UIStackView() | |
stack.axis = .horizontal | |
stack.distribution = .fillEqually | |
stack.spacing = 8 | |
return stack | |
}() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
setupUI() | |
} | |
func setupUI() { | |
[plusButton, minusButton, countLabel, mainStack, buttonStack].forEach { | |
$0.translatesAutoresizingMaskIntoConstraints = false | |
} | |
buttonStack.addArrangedSubview(minusButton) | |
buttonStack.addArrangedSubview(plusButton) | |
view.addSubview(buttonStack) | |
mainStack.addArrangedSubview(countLabel) | |
mainStack.addArrangedSubview(buttonStack) | |
view.addSubview(mainStack) | |
NSLayoutConstraint.activate([ | |
mainStack.centerXAnchor.constraint(equalTo: view.centerXAnchor), | |
mainStack.centerYAnchor.constraint(equalTo: view.centerYAnchor) | |
]) | |
plusButton.addTarget(self, action: #selector(counter), for: .touchUpInside) | |
minusButton.addTarget(self, action: #selector(counter), for: .touchUpInside) | |
} | |
@objc func counter(_ sender: UIButton) { | |
if sender.tag == 1 { | |
count += 1 | |
} | |
if sender.tag == 2 && count > 0 { | |
count -= 1 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment