SwiftUI中如何为自定义View扩展.stringOfText()链式调用方法?
To achieve the chainable method syntax you want (customText().stringOfText("Omid")), we’ll create a modifier-style extension method for your custom view. Here’s a step-by-step breakdown:
Step 1: Adjust the Custom View
First, remove the @State property wrapper from stringOfText (since we’re setting this value externally, not managing internal state) and set a default value. Also, follow Swift’s naming convention by using PascalCase for the struct name (CustomText instead of customText):
struct CustomText: View { var stringOfText: String = "Hello, world!" // Default text value var body: some View { Text(stringOfText) } }
Step 2: Add the Extension Method
Create an extension on CustomText that returns a modified instance of the view with the updated text. Since SwiftUI views are value types, we make a mutable copy of the current instance, update the property, then return the copy:
extension CustomText { func stringOfText(_ text: String) -> CustomText { var modifiedView = self modifiedView.stringOfText = text return modifiedView } }
Step 3: Use the Chained Method in ContentView
Now you can use the method exactly as you requested:
struct ContentView: View { var body: some View { CustomText().stringOfText("Omid") } }
Why This Works
- The extension method uses Swift’s value semantics: modifying
modifiedViewcreates a new instance ofCustomTextwith the updatedstringOfTextvalue, which fits perfectly with SwiftUI’s immutable view pattern. - This approach gives you the clean, chainable syntax you want without needing
@Bindingor other state management tools (as specified in your request).
内容的提问来源于stack exchange,提问作者swiftPunk

