How to make view the size of another view in SwiftUI

后端 未结 7 2015
忘掉有多难
忘掉有多难 2020-11-29 18:31

I\'m trying to recreate a portion of the Twitter iOS app to learn SwiftUI and am wondering how to dynamically change the width of one view to be the width of another view. I

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 18:46

    Here's a super simple solution, although it doesn't account for the tabs being stretched full width - but that should just be minor additional math for calculating the padding.

    import SwiftUI
    
    struct HorizontalTabs: View {
    
      private let tabsSpacing = CGFloat(16)
    
      private func tabWidth(at index: Int) -> CGFloat {
        let label = UILabel()
        label.text = tabs[index]
        let labelWidth = label.intrinsicContentSize.width
        return labelWidth
      }
    
      private var leadingPadding: CGFloat {
        var padding: CGFloat = 0
        for i in 0..

    HorizontalTabs(tabs: ["one", "two", "three"]) renders this:

提交回复
热议问题