在Swift4中创建函数以编程方式从字符串数组创建UILabel

时间:2019-04-29 06:00:13

标签: ios swift uilabel

我能够以编程方式创建UILabel,但是在创建函数时是否必须将其放入viewDidLoad()方法中?我需要使用self.view.addSubview(label)将标签附加到视图中,但是会引发错误,并且当标签不在viewDidLoad()之外时,构建将失败。

每当我尝试在viewDidLoad方法之外创建函数时,都会声明“使用未解析的标识符自身”。有没有办法解决?

此外,当我确实将函数放在viewDidLoad中时,一切工作正常,并且创建了标签,但它们是在彼此之上创建的。如果可能的话,我希望标签彼此相邻吗?

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    func createALabel(inputtedString: String) -> Void {
        let string = inputtedString
        let test = string.components(separatedBy: " ")

        for element in test {
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
            label.center = CGPoint(x: 160, y: 285)
            label.textAlignment = .center
            label.textColor = UIColor.blue
            label.text = element
            label.layer.borderColor = UIColor.blue.cgColor
            label.layer.borderWidth = 3.0
            self.view.addSubview(label)
        }
    }
}

Even with the position change my labels are still stacking

3 个答案:

答案 0 :(得分:1)

管理这样的几何图形UIStackView可能很有用。 另外,您不需要在viewDidLoad中调用此方法,当您要初始化和管理视图时,loadView生命周期方法对此更合适。 以编程方式。

class ViewController: UIViewController {
    private let vstackView = UIStackView()
    private let horizontal_spacing = 20.0
    private let spaceConstantForLetter = 10.0

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        vstackView.axis = .vertical
        vstackView.translatesAutoresizingMaskIntoConstraints = false
        vstackView.alignment = .center
        vstackView.spacing = 10

        self.view.addSubview(vstackView)
        vstackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        vstackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true


        createALabel(inputtedString: "this is a long test string that exceeds screen width")//
        // Do any additional setup after loading the view.

    }


    func createALabel(inputtedString: String) -> Void {
        let string = inputtedString
        let test = string.components(separatedBy: " ")


        var horizontalStackList = [UILabel] ()

        for (index, element) in test.enumerated() {
            let label = UILabel()
            label.textAlignment = .center
            label.textColor = UIColor.blue
            label.text = element
            label.layer.borderColor = UIColor.blue.cgColor
            label.layer.borderWidth = 1.0
            horizontalStackList.append(label)

            let totalLetterNumber = horizontalStackList.map { $0.text!.count }.reduce(0, +)

            let contentWidth = Double(totalLetterNumber) * spaceConstantForLetter //constant for a letter that takes how much space from screen
            let spacingWidth = Double(horizontalStackList.count - 1) * horizontal_spacing
            /*add left and right margins if exist*/
            if((CGFloat(spacingWidth + contentWidth) > UIScreen.main.bounds.width)  || index == test.count - 1) {
                let exceedingLabel = horizontalStackList.popLast()
                let hstackView = UIStackView(arrangedSubviews: horizontalStackList)
                hstackView.axis = .horizontal
                hstackView.translatesAutoresizingMaskIntoConstraints = false
                hstackView.spacing = CGFloat(horizontal_spacing)
                hstackView.alignment = .center
                vstackView.addArrangedSubview(hstackView)
                horizontalStackList.removeAll(keepingCapacity: false)
                horizontalStackList.append(exceedingLabel!)
            }

        }
    }
}

编辑:自动换行添加为Jazzin想要的

output of the code above

答案 1 :(得分:1)

使用收藏夹视图是最佳选择。它使您的工作更加轻松。试试这个

date = commits[i]['Date']  
print("commited date:", date) 
moduleDate.append(date)
upToDateModule = max(moduleDate) #trigger here

Traceback (most recent call last):   File
"/home/savoiui/PycharmProjects/VersionChecker/versionCheckerV4.py",
line 120, in <module>
    main()   File "/home/savoiui/PycharmProjects/VersionChecker/versionCheckerV4.py",
line 110, in main
    upToDateModule = max(moduleDate)
 TypeError: an integer is required (got type str)

enter image description here

答案 2 :(得分:0)

您必须添加一个Integer变量来设置x位置。在这里,我根据设置的x位置设置了xPos变量

class ViewController: UIViewController {

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
        }

        func createALabel(inputtedString: String) -> Void {
            let string = inputtedString
            let test = string.components(separatedBy: " ")

             let xPos = 0
            for element in test {
                let label = UILabel(frame: CGRect(x: xPos, y: 0, width: 60, height: 35))
               // label.center = CGPoint(x: 160, y: 285)
                label.textAlignment = .center
                xPos = xPos + 60 + 10   // Update xPos width 60 & 10 is gap between two label
                label.textColor = UIColor.blue
                label.text = element
                label.layer.borderColor = UIColor.blue.cgColor
                label.layer.borderWidth = 3.0
                self.view.addSubview(label)
            }
        }
    }