Swift – Cannot use custom view in SwiftUI

swiftswiftui

For my SwiftUI application, I've created a simple Title view, that has a set font size and text color. Title is declared as follows:

struct Title: View {
    var string: String
    
    var body: some View {
        Text(string)
            .font(.system(size: 32))
            .color(Color.black)
    }
}

I have the following text objects in my content view's body right now:

var body: some View {
    VStack(alignment: .leading) {
        Text("Welcome")
            .font(.largeTitle)
            .color(Color.black)
        Text("to SwiftUI")
            .font(.largeTitle)
            .color(Color.secondary)
    }
}

So now, I want to replace these two Texts with my Titles:

var body: some View {
    VStack(alignment: .leading) {
        Title("Welcome")
        Title("to SwiftUI")
    }
}

After replacing the views, I'm getting some seemingly unrelated error messages from Xcode, that stop the application from compiling:

Static member 'leading' cannot be used on instance of type 'HorizontalAlignment'

'(LocalizedStringKey) -> Text' is not convertible to '(LocalizedStringKey, String?, Bundle?, StaticString?) -> Text'

'Font' is not convertible to 'Font?'

…and more. Reverting back to Text instead of Title "fixes" the issues.

What's interesting is that I also have a custom PrimaryButton view that I was able to add without any issues:

struct PrimaryButton: View {
    var title: String
    
    var body: some View {
        Button(action: { print("tapped") }) {
            Text(title)
                .font(Font.primaryButton)
                .offset(y: 1)
                .padding(.horizontal, 20)
                .padding(.vertical, 14)
        }
    }
}

…and then using it:

PrimaryButton(title: "Let's go")

Question

Is this simply a beta-issue, or am I missing something?

Best Answer

You need to add string: to your Title() initializer:

var body: some View {
    VStack(alignment: .leading) {
        Title(string: "Welcome")
        Title(string: "to SwiftUI")
    }
}

Compiler errors are currently misleading and not located near where the real issue is.

Related Topic