其他分享
首页 > 其他分享> > SwiftUI 小技巧之 对齐扩展组件AlignmentID

SwiftUI 小技巧之 对齐扩展组件AlignmentID

作者:互联网

实战代码

SwiftUI 对齐扩展组件AlignmentID

解决方案

import SwiftUI

// 定义方式
extension HorizontalAlignment {
    enum NoteCenter: AlignmentID {
        static func defaultValue(in context: ViewDimensions) -> CGFloat {
            context[HorizontalAlignment.center]
        }
    }

    static let noteCenter = HorizontalAlignment(NoteCenter.self)
}

// 调用方式
struct MainNoteView: View {
    let note: String
    var body: some View {
        Text(note)
            .font(.system(size: 160, design: .rounded))
            .bold()
            .alignmentGuide(.noteCenter) { dimensions in
                dimensions[HorizontalAlignment.center]
            }
    }
}

struct MainNoteView_Previews: PreviewProvider {
    static var previews: some View {
        MainNoteView(note: "A")
            .previewLayout(.sizeThatFits)
    }
}


加入我们一起学习SwiftUI

QQ:3365059189
SwiftUI技术交流QQ群:518696470
教程网站:www.openswiftui.com

标签:AlignmentID,note,SwiftUI,static,HorizontalAlignment,MainNoteView,对齐
来源: https://blog.csdn.net/iCloudEnd/article/details/116884967