我想添加标签。我应该在哪里编写代码来添加标签?
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var x = 20.0
var y = 100.0
let width = 100.0
let offsetX = 80.0
let offsetY = 80.0
for i in 1 ... 9 {
let button = UIButton(frame: CGRect(x: x, y: y, width: width, height: width))
button.tag = i
button.setTitle("\(i)", for: UIControlState.normal)
button.setTitleColor(UIColor.green, for: UIControlState.normal)
button.addTarget(self, action: #selector(self.buttonPressed(button:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(button)
x = x + offsetX
if i%3 == 0 {
y = y + offsetY
x = 20.0
}
}
}
@objc func buttonPressed (button:UIButton) {
print("Button Pressed: \(button.tag)")
}
}
答案 0 :(得分:0)
let lblNew = UILabel(frame: CGRect(x: x, y: y, width: width, height: width))
lblNew.backgroundColor = UIColor.clear
lblNew.text = "Label Text"
lblNew.textColor = UIColor.black
view.addSubview(lblNew)
答案 1 :(得分:0)
如果您只是想添加标签。您可以使用以下代码。
window
如果您想添加每个按钮。你可以放入循环并相应地改变x和y的值。