12
votes

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?

3

3 Answers

13
votes

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.

3
votes

You are missing the string: param in the initializer. Please find the updated code below:

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

FYI:
I have created one sample application

// MARK - CustomView

struct ContentView : View {
    var body: some View {
        VStack{
            CustomView(aString: "First String")
            CustomView(aString: "Second String")
        }
    }
}

// MARK - CustomView

struct CustomView : View {
    var aString: String
    var body: some View {
        Text(aString)
    }
}
0
votes

Today, 01oct2019, Swift prompted me to replace string: with. verbatim: .

Text(verbatim: "Pressure") works today Text(string: "Pressure") did work yesterday but not today. hth