如何在 swift 中使用 for 循环以编程方式创建按钮
How to create a button programmatically with for loop in swift
我用 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")
}
各种方法...
- 找到点击按钮的框架(不是一个好方法,但对于您的简单示例它可以工作)
- 使用按钮
.tag
属性
- 评价按钮的
.currentTitle
属性
- 将按钮添加到数组...点击时,使用
let buttonNumber = btnsArray.firstIndex(of: sender)
方法有很多种,但是'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)
}
}
}
我用 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")
}
各种方法...
- 找到点击按钮的框架(不是一个好方法,但对于您的简单示例它可以工作)
- 使用按钮
.tag
属性 - 评价按钮的
.currentTitle
属性 - 将按钮添加到数组...点击时,使用
let buttonNumber = btnsArray.firstIndex(of: sender)
方法有很多种,但是'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)
}
}
}