skip to Main Content

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


  1. Various ways to do that…

    1. find the frame of the tapped button (not a good approach, but for your simple example it could work)
    2. use the .tag property of the button
    3. evaluate the .currentTitle property of the button
    4. add the buttons to an array… on tap, use let buttonNumber = btnsArray.firstIndex(of: sender)
    Login or Signup to reply.
  2. There are lots of ways, but a ‘Swifty’ way might be like this:

    final class TargetAction {
        let work: () -> Void
    
        init(_ work: @escaping () -> Void) {
            self.work = work
        }
    
        @objc func action() {
            work()
        }
    }
        
    class ViewController: UIViewController {
        private var tas: [TargetAction] = []
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            (0...4).forEach { x in
                let button = UIButton(frame: CGRect(x: CGFloat(x) * 50 , y: 40, width: 44, height: 44))
                button.setTitleColor(.black, for: .normal)
                button.setTitle("(x)", for: .normal)
                let ta =
                    TargetAction {
                        print(x)
                    }
                tas.append(ta)
                button.addTarget(ta, action: #selector(TargetAction.action), for: .touchUpInside)
                view.addSubview(button)
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search