簡體   English   中英

iOS與Java / Swing的FlowLayout等效嗎?

[英]What is iOS's equivalent of Java/Swing's FlowLayout?

我正在嘗試構建一個UIView ,該UIView使用其固有寬度從左到右UIView其他視圖,然后在必要時進行包裝。 對於我所需要的, UICollectionView似乎過於復雜。 我也嘗試過將FlexLayout包裝器用於Yoga,但似乎無法獲得正確的咒語。 似乎比這要容易得多-什么是簡單的解決方案?

我最終編寫了自己的UIView來解決問題。 我懷疑它是否非常健壯,但是可以解決我的迫切需求。 如果您有任何改進建議,請發表評論。

import UIKit

class FlowLayout: UIView {
private var hgapValue: CGFloat = 0.0
private var vgapValue: CGFloat = 0.0

var hgap: CGFloat {
    set(newValue) {
        hgapValue = (newValue < 0) ? -newValue : newValue
    }
    get {
        return hgapValue
    }
}

var vgap: CGFloat {
    set(newValue) {
        vgapValue = (newValue < 0) ? -newValue : newValue
    }
    get {
        return vgapValue
    }
}

//initWithFrame to init view from code
override init(frame: CGRect) {
    super.init(frame: frame)
    setupView()
}

//initWithCode to init view from xib or storyboard
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setupView()
}

override func didAddSubview(_ subview: UIView) {
    refreshLayout()
}

//common func to init our view
private func setupView() {
    // backgroundColor = .red
}

public func refreshLayout() {
    var x: CGFloat = 0.0
    var y: CGFloat = 0.0

    for subview in subviews {
        subview.frame.origin.x = x
        subview.frame.origin.y = y
        x += subview.frame.width + hgapValue
        if x + subview.frame.width >= (subview.superview?.frame.width)! {
            x = 0.0
            y += subview.frame.height + vgapValue
        }

    }
    setNeedsDisplay()
}

}

在界面生成器中,使用UIStackView實現一個簡單的替代方法。

您也可以打開自動布局以使其自然。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM