I created buttons with for loop and i want to print button number when pressed to button. How can i do this?
for x in 0..<5 {
let button = UIButton(frame: CGRect(x: CGFloat(x) * view.frame.size.width + 10 , y: 40, width: view.frame.size.width - 20, height: 30))
buttonKontrol = x
print(buttonKontrol)
button.setTitle("Button", for: .normal)
button.backgroundColor = .white
button.setTitleColor(.black, for: .normal)
button.addTarget(self, action: #selector(btntapped), for: .touchUpInside)
scrollView.addSubview(button)
}
and objc func:
@objc func btntapped(_ sender: UIButton) {
print("button tapped")
}
2
Answers
Various ways to do that…
.tag
property of the button.currentTitle
property of the buttonlet buttonNumber = btnsArray.firstIndex(of: sender)
There are lots of ways, but a ‘Swifty’ way might be like this: