繁体   English   中英

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

[英]Creating a function to programmatically create UILabels from a String Array in Swift4

我可以以编程方式创建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)
        }
    }
}

即使改变位置,我的标签仍在堆叠

为了管理这样的几何图形, 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!)
            }

        }
    }
}

编辑:换行添加为爵士想要

上面代码的输出

最好使用收集视图。 它使您的工作更加轻松。 尝试这个

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var wordsArr = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        collectionView.backgroundColor = .white
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(WordCell.self, forCellWithReuseIdentifier: "WordCell")
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(collectionView)
        view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(5)-[collectionView]-(5)-|", options: [], metrics: nil, views: ["collectionView":collectionView]))
        view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(5)-[collectionView]-(5)-|", options: [], metrics: nil, views: ["collectionView":collectionView]))

        createALabel(inputtedString: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam")
    }
    func createALabel(inputtedString: String) -> Void {
        wordsArr = inputtedString.components(separatedBy: " ")
        collectionView.reloadData()
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return wordsArr.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WordCell", for: indexPath) as? WordCell ?? WordCell()
        cell.label.text = wordsArr[indexPath.row]
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (wordsArr[indexPath.row] as NSString).boundingRect(with: CGSize.zero, options: .usesLineFragmentOrigin, attributes: [.font: UIFont.systemFont(ofSize: 16.0)], context: nil).size.width
        let size = CGSize(width: width + 10
            , height: 35)
        return size
    }

}
class WordCell: UICollectionViewCell {

    let label = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    func commonInit() {

        backgroundColor = .white

        label.font = UIFont.systemFont(ofSize: 16.0)
        label.textAlignment = .center
        label.textColor = UIColor.blue
        label.layer.borderColor = UIColor.blue.cgColor
        label.layer.borderWidth = 3.0
        label.translatesAutoresizingMaskIntoConstraints = false
        addSubview(label)

        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[label(35)]|", options: [], metrics: nil, views: ["label":label]))
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[label]|", options: [], metrics: nil, views: ["label":label]))
    }
}

在此处输入图片说明

您必须添加一个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)
            }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM