美文网首页
iOS UIStackView的使用

iOS UIStackView的使用

作者: 玉思盈蝶 | 来源:发表于2020-05-09 17:48 被阅读0次
    //
    //  StackViewController.swift
    //  Swift_shop
    //
    //  Created by 彭思 on 2020/5/9.
    //  Copyright © 2020 HaiDilao. All rights reserved.
    //
    
    import UIKit
    
    class StackViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.view.backgroundColor = UIColor.white
            layoutStackView()
        }
        
        func layoutStackView() {
            let stackView = stackViewWithAxis(axis: .vertical, alignment: .fill, distribution: .fill)
            view.addSubview(stackView)
            stackView.snp.makeConstraints { (make) in
                make.center.equalTo(self.view)
                make.left.equalTo(10)
                make.right.equalTo(-10)
            }
            for i in 0..<3 {
                let label = createLabel()
                label.text = "\("哈哈")" + "\(i)"
                stackView.addArrangedSubview(label)
                label.snp.makeConstraints { (make) in
                    make.height.greaterThanOrEqualTo(50)
                }
            }
        }
        
        func stackViewWithAxis(axis: NSLayoutConstraint.Axis, alignment: UIStackView.Alignment, distribution: UIStackView.Distribution) -> UIStackView {
            let stackView = UIStackView()
            stackView.axis = axis
            stackView.alignment = alignment
            stackView.distribution = distribution
            return stackView
        }
        
        func createLabel() -> UILabel {
            let label = UILabel()
            label.textColor = UIColor.black
            label.numberOfLines = 0
            label.backgroundColor = UIColor.init(red: CGFloat(arc4random_uniform(256))/255.0, green: CGFloat(arc4random_uniform(256))/255.0, blue: CGFloat(arc4random_uniform(256))/255.0, alpha: 1.0)
            return label
        }
    
    }
    

    效果图如下:

    image.png

    相关文章

      网友评论

          本文标题:iOS UIStackView的使用

          本文链接:https://www.haomeiwen.com/subject/liqlnhtx.html