我的视图结构非常复杂,有很多不同的子视图,到目前为止,我把它们都放在一个文件中,但它变得像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
结构,因为它被标记为私有,并且只在文件范围内有效。
1条答案
按热度按时间4nkexdtk1#
要组织代码,可以使用@ViewBuilder:
并调用函数体中的函数:
也可以使用自定义视图修饰符,如下所示:
然后你就可以这样使用它: