xcode 在单独文件中为视图的子视图和常量创建私有扩展

kyvafyod  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(127)

我的视图结构非常复杂,有很多不同的子视图,到目前为止,我把它们都放在一个文件中,但它变得像400多行代码一样大(我使用SwiftLint来检查代码规则的破坏),所以我想到将这些子视图和常量移动到单独的文件中,并创建一个扩展。我想要的是,扩展只对它扩展的特定视图可见,而且这个扩展可以保存在单独的文件中,以减少原始视图文件中的代码行:
示例:
"到目前为止,我的处境是这样的“
File SampleView

struct SampleView: View {
    var body: some View {
        VStack {
            SampleView.SampleViewConstants.sampleImage
        }
    }
}

private extension SampleView {
    static var sampleImage: some View {
        Image(SampleViewConstants.imageName)
                .resizable()
                .frame(height: SampleViewConstants.imageBackgroundFrameHeight)
                .frame(maxWidth: .infinity)
    }
    
    struct SampleViewConstants {
        static let imageName: String = "sampleImageName"
        static let imageBackgroundFrameHeight: CGFloat = 56
    }
}

我想要的:

File SampleView

struct SampleView: View {
    var body: some View {
        VStack {
            SampleView.SampleViewConstants.sampleImage
        }
    }
}

File SampleViewConstants

private extension SampleView {
    static var sampleImage: some View {
        Image(SampleViewConstants.imageName)
                .resizable()
                .frame(height: SampleViewConstants.imageBackgroundFrameHeight)
                .frame(maxWidth: .infinity)
    }
    
    struct SampleViewConstants {
        static let imageName: String = "sampleImageName"
        static let imageBackgroundFrameHeight: CGFloat = 56
    }
}

不幸的是,XCode告诉我,我的SampleView没有看到SampleViewConstants结构,因为它被标记为私有,并且只在文件范围内有效。

4nkexdtk

4nkexdtk1#

要组织代码,可以使用@ViewBuilder:

@ViewBuilder func sampleView(name: String = "sampleImageName", height: CGFloat = 56) -> some View {
    let imageName = name
    let imageBackgroundFrameHeight = height
    
    VStack {
        Image(imageName)
            .resizable()
            .frame(height: imageBackgroundFrameHeight)
            .frame(maxWidth: .infinity)
    }
}

并调用函数体中的函数:

sampleView() //This will take the default values(imageName = "sampleImageName" and imageBackgroundFrameHeight = 56)

sampleView(name: "NewName", height: 80) //This will take on new values "NewName" and height of 80

也可以使用自定义视图修饰符,如下所示:

struct Shadowfy: ViewModifier {
    func body(content: Content) -> some View {
        content // The content is a view you want to put your custom modifier on like my shadowfy custom modifier that puts shadows on views so I don't have to repeat this code
            .shadow(color: .red, radius: 1, x: 1, y: -1)
            .shadow(color: .green, radius: 2, x: -2, y: 2)
    }
}
extension View { 
    func shadowfy() -> some View { 
        self.modifier(Shadowfy())
     }
 }

然后你就可以这样使用它:

Text("MyText")
    .shadowfy()

相关问题