使用swift第三方库Cartography实现微博九宫格

Cartography是用swift编写的autolayout开源库。
为了测试编写了一个微博九宫格的demo,以便展示Cartography的功能!
demo代码如下:


    let numForCol: Int = 3
    let spacing: CGFloat = 15
    let showView = UIView.init()
    
    func random() -> Int{// 1-9
        return Int(arc4random()%9)+1
    }
    
    func randomColor() -> UIColor{
        let red = CGFloat(arc4random_uniform(255))/CGFloat(255.0)
        let green = CGFloat(arc4random_uniform(255))/CGFloat(255.0)
        let blue = CGFloat(arc4random_uniform(255))/CGFloat(255.0)
        return UIColor.init(red:red, green:green, blue:blue , alpha: 1)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "刷新", style: UIBarButtonItemStyle.done, target: self, action: #selector(refreshShowView))
        
        showView.backgroundColor = UIColor.gray
        self.view.addSubview(showView)
        
        constrain(showView) { view in
            view.top >= topLayoutGuideCartography// 如果有navigationBar可以使用topLayoutGuideCartography属性,避开上面的导航栏,与autolayout中的topLayoutGuide功能一致
            view.centerY >= view.superview!.centerY
            view.left == view.superview!.left
            view.width == view.superview!.width
            view.height == view.width ~ 100
        }
        refreshShowView()
    }
    
    func refreshShowView(){
        
        _ = showView.subviews.map{$0.removeFromSuperview()}
        
        for index in 0..

使用swift第三方库Cartography实现微博九宫格_第1张图片
autolayout布局图

demo地址: https://github.com/fengyunjue/jiugongge

你可能感兴趣的:(使用swift第三方库Cartography实现微博九宫格)