SwiftUI:如何强制将HStack中的特定视图置于中心

时间:2020-06-15 14:19:50

标签: swiftui alignment hstack

给出如下所示的HStack:

did you mean...

如何强制“中心”视图居中?

2 个答案:

答案 0 :(得分:4)

这里可能是简单的方法。使用Xcode 11.4 / iOS 13.4进行了测试

demo

...

const submitted_at = threads[0].data.submitted_at.toDate();
const ref = firestore()
        .collection('Discover')
        .where('submitted_at', '>', `${submitted_at}`)
// Also tried comparing using new Date(submitted_at) but it still did not work
        .orderBy('submitted_at', 'desc')
        .limit(10);
...

Position view relative to a another centered view

中提供了带有左对齐/右对齐的解决方案的解决方案

答案 1 :(得分:3)

答案需要几个步骤

  1. 将HStack包裹在VStack中。 VStack可以控制 子级水平对齐
  2. 将自定义对齐指南应用于VStack
  3. 创建采用全宽度的VStack的子视图。将自定义对齐向导固定到此视图的中心。 (这会将对齐向导固定在VStack的中心)
  4. 将“中心”视图的中心与对齐指南对齐

对于必须填充VStack的视图,我使用了Geometry Reader。这样会自动扩展为采用父级的尺寸,而不会干扰布局。

import SwiftUI


//Custom Alignment Guide
extension HorizontalAlignment {
    enum SubCenter: AlignmentID {
        static func defaultValue(in d: ViewDimensions) -> CGFloat {
            d[HorizontalAlignment.center]
        }
    }

    static let subCentre = HorizontalAlignment(SubCenter.self)
}

struct CentreSubviewOfHStack: View {
    var body: some View {
        //VStack Alignment set to the custom alignment
        VStack(alignment: .subCentre) {
            HStack{
                Text("View1")

                //Centre view aligned
                Text("Centre")
                .alignmentGuide(.subCentre) { d in d.width/2 }

                Text("View2")

                Text("View3")
            }

            //Geometry reader automatically fills the parent
            //this is aligned with the custom guide
            GeometryReader { geometry in
                EmptyView()
            }
            .alignmentGuide(.subCentre) { d in d.width/2 }
        }
    }
}

struct CentreSubviewOfHStack_Previews: PreviewProvider {
    static var previews: some View {
        CentreSubviewOfHStack()
            .previewLayout(CGSize.init(x: 250, y: 100))
    }
}

Centre is in the centre