首页 > 解决方案 > ios swift flexlayout在添加项目后获取flex的高度

问题描述

以下是我在 flex 布局中添加项目的代码https://github.com/layoutBox/FlexLayout

        rootFlexContainer.flex.direction(.row).wrap(.wrap).alignSelf(.auto).justifyContent(.start).paddingRight(2).define { (flex) in
        for i in 0..<((retailerTags?.count ?? 0) > 3 ? 3 : (retailerTags?.count ?? 0)) {
            let nameLabel = UIButton()
            nameLabel.isUserInteractionEnabled = false
            nameLabel.setTitle((retailerTags?[i] ?? "").trim(), for: .normal)
            nameLabel.setTitleColor(.black, for: .normal)
            nameLabel.titleLabel?.font = FontStyle.ProximaNovaRegular(size: 11)
            nameLabel.contentEdgeInsets = UIEdgeInsets(top: 1.5, left: 4, bottom: 1.5, right:4)
            nameLabel.layer.borderColor = UIColor.hexStringToUIColor(hex: TravelXStrings.grayBorderColor).cgColor
            nameLabel.layer.cornerRadius = 8
            nameLabel.layer.borderWidth = 1.0
            flex.addItem(nameLabel).margin(2)
            
           
        }
        if cashbackString != "" {
        let cashbackLabel = UIButton()
            
            cashbackLabel.backgroundColor = UIColor.hexStringToUIColor(hex: TravelXStrings.orangeCashbackColor)
            cashbackLabel.isUserInteractionEnabled = false
            cashbackLabel.setTitle(cashbackString, for: .normal)
            cashbackLabel.setTitleColor(.black, for: .normal)
            cashbackLabel.titleLabel?.font = FontStyle.ProximaNovaRegular(size: 10)
            cashbackLabel.contentEdgeInsets = UIEdgeInsets(top: 1.5, left: 5, bottom: 1.5, right: 5)
            cashbackLabel.layer.cornerRadius = 8
            cashbackLabel.layer.borderWidth = 0
            flex.addItem(cashbackLabel).margin(2)
        }
 
        
    }
    

添加视图后,我无法在尝试使用bounds.height、flex.intrinsicSize.height添加元素后不久获得此 rootflex 容器的高度,但高度返回错误,仅在方法 layoutSubviews() 中获取精确高度

 override func layoutSubviews() {
    super.layoutSubviews()
    layout()
}

fileprivate func layout() {
    rootFlexContainer.frame.size.width = frame.width - 20
    rootFlexContainer.flex.layout(mode: .adjustHeight)
    if(rootFlexContainer.frame.height ! = 0){
        tagsHeight.constant = rootFlexContainer.frame.height
    }
    //tagsView.flex.layout(mode: .adjustWidth)
}

如何在调用layoutSubviews之前和添加元素后不久获得准确的 flex 布局高度?

标签: iosswiftflexboxconstraintslayoutsubviews

解决方案


推荐阅读