UIButton是iOS开发中常用的交互控件,循环创建多个UIButton是常见的界面开发需求。循环创建可以避免重复代码,提高开发效率。
for i in 0..<5 {
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 100 + i * 60, width: 200, height: 50)
button.setTitle("按钮 \(i+1)", for: .normal)
button.backgroundColor = .lightGray
button.tag = i // 设置tag以便区分不同按钮
button.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
view.addSubview(button)
}
@objc func buttonClicked(_ sender: UIButton) {
print("点击了按钮 \(sender.tag + 1)")
}
var buttons = [UIButton]()
for i in 0..<5 {
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 100 + i * 60, width: 200, height: 50)
button.setTitle("按钮 \(i+1)", for: .normal)
button.tag = i
buttons.append(button)
view.addSubview(button)
}
var previousButton: UIButton?
for i in 0..<5 {
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("按钮 \(i+1)", for: .normal)
button.tag = i
view.addSubview(button)
NSLayoutConstraint.activate([
button.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
button.heightAnchor.constraint(equalToConstant: 50)
])
if let prev = previousButton {
button.topAnchor.constraint(equalTo: prev.bottomAnchor, constant: 20).isActive = true
} else {
button.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
}
previousButton = button
}
原因:
解决方案:
原因:
解决方案:
原因:
解决方案:
通过循环创建UIButton可以大大提高开发效率,特别是在需要创建大量相似按钮的场景中。
没有搜到相关的文章