【问题标题】:How to create a button programmatically with for loop in swift如何在swift中使用for循环以编程方式创建按钮
【发布时间】:2021-03-31 20:38:57
【问题描述】:

我使用 for 循环创建了按钮,并且我想在按下按钮时打印按钮编号。我该怎么做?

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)
}

和 objc 函数:

@objc func btntapped(_ sender: UIButton) {
    print("button tapped")
}

【问题讨论】:

    标签: ios swift objective-c xcode for-loop


    【解决方案1】:

    有多种方法可以做到这一点...

    1. 找到点击按钮的框架(不是一个好方法,但对于您的简单示例,它可以工作)
    2. 使用按钮的.tag 属性
    3. 评估按钮的.currentTitle 属性
    4. 将按钮添加到数组中...点击时,使用let buttonNumber = btnsArray.firstIndex(of: sender)

    【讨论】:

      【解决方案2】:

      有很多方法,但“Swifty”的方法可能是这样的:

      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)
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-17
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-27
        相关资源
        最近更新 更多