Swift-如何动态创建标签

时间:2018-03-19 19:29:39

标签: arrays swift arraylist uilabel

我创建了一些代码,它读取数组并将每个索引的数据保存到变量中,然后传递给创建的标签。

以下是代码: 数据arr内容的示例: ["2,5","5,1"]数组中的两个索引

for i in 0..<dataArr.count {
let element = dataArr[i]
let labelNum = UILabel()
label split = element.components(separatedBy: ",")

let num1 = split[0]
let num2 = split[1]

let num1Nnum2 = "number 1 :" + num1 + " number 2:" + num2
labelnum.text = num1Nnum2
labelnum.textAlignment = .center
labelnum.frame = CGRect( x:10, y:90, width:250, height: 80)
self.view.addSubview(labelnum)

}

如何创建它以便在第二次创建标签时读取索引[1]时,它会创建一个具有相同代码的新标签,但将标签放在第一个标签下。我试过这样做:

labelnum [i]尝试使用index的值创建新标签,例如当i = 1时,使用labelnum1。

任何帮助都会得到赞赏。

2 个答案:

答案 0 :(得分:1)

创建一个变量来保存标签的Y位置。并在每次迭代中添加Y Position变量中前一个标签的高度,以将新标签拖放到前一个标签下方。

class ViewController: UIViewController {

let dataArr = ["2,5","5,1"]
override func viewDidLoad() {
    super.viewDidLoad()
    var yPos = 90
    for i in 0..<dataArr.count {
        let element = dataArr[i]
        let labelNum = UILabel()
        let split = element.components(separatedBy: ",")

        let num1 = split[0]
        let num2 = split[1]

        let num1Nnum2 = "number 1 :" + num1 + " number 2:" + num2
        labelNum.text = num1Nnum2
        labelNum.textAlignment = .center
        labelNum.frame = CGRect( x:10, y:yPos, width:250, height: 80)
        yPos += 80
        self.view.addSubview(labelNum)

    }

}

答案 1 :(得分:1)

iOS中有 UIStackView ,可让您在现有视图的底部或顶部动态添加元素。您始终可以添加一个自动显示在视图底部的新标签。您也可以使用 UITableView UIScrollView 来完成此操作。

以下是 UIStackView 的示例,动态地在上一个标签下面附加新标签。我希望你能为你的用例推断出这个,​​

class ViewController: UIViewController {

    var lastLabelCount = 0

    var stackView: UIStackView!

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        let tap = UITapGestureRecognizer(target: self,
                                         action: #selector(tapped))
        view.addGestureRecognizer(tap)
        createViews()
    }

    func createViews() {
        stackView = UIStackView(frame: .zero)
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.axis = .vertical
        stackView.alignment = .top
        view.addSubview(stackView)

        NSLayoutConstraint.activate([
            stackView.leftAnchor.constraint(equalTo: view.leftAnchor),
            stackView.rightAnchor.constraint(equalTo: view.rightAnchor),
            stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            ])
    }

    @objc func tapped() {
        let label = UILabel(frame: .zero)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = UIColor.black
        label.text = "Hi I am label \(lastLabelCount)"
        stackView.addArrangedSubview(label)

        lastLabelCount += 1
    }
}