'Change text alignment of DatePicker in SwiftUI 2.0 iOS 14
Is it currently possible to change the text alignment of a DatePicker in SwiftUI 2.0?
DatePicker(selection: $birthDate, in: ...Date().stripTime(), displayedComponents: .date) {
Text("Birthday")
}
This shows Birthday text on the left and the Date picker text right next to it but I would like it on the right side
Solution 1:[1]
My suggestion would be to include the required items in a VStack with alignment and spacing set. This keeps everything inside the VStack left aligned.
I would remove the Spacer() as this pushes the second item up to the right margin.
VStack (alignment: .leading, spacing: 8) {
HStack {
Text("Birthday")
// some other spacer
DatePicker("", selection: $birthDate, in: ...Date().stripTime(),displayedComponents: .date)
.fixedSize()
}
}
Solution 2:[2]
On the INamedTypeSymbol/member/whatever that has the attributes, you can call GetAttributes(), which gives you an array of AttributeDatas. That'll give you all the attributes for that, so you'll have to filter back to your attribute type. That AttributeData also gives you two properties:
- NamedArguments which covers your
Property = ...syntax - ConstructorArguments which is the array of the arguments as being passed to the constructor. You can figure out which constructor it is looking at the AttributeConstructor property. If you want to say "give me the argument for the constructor parameter named foo", figure out the index of the argument in the constructor and then look at that same index in the ConstructorArguments collection.
Solution 3:[3]
According to a friend of mine:
There doesn't seem to be any public API to get the resolved attribute object or a copy of it. The closest thing is SemanticModel.GetReferencedDeclaration which gives you the declaration the attribute is on but not the attribute itself. You can get the attribute's name from the declaration's Name property and the attribute's type from the Type property, so you could write some code like this:
var attribute = declaration.GetReferencedDeclaration().Type.GetGenericTypeArguments()[0];
var first = int.Parse(attribute.Name.Substring(0, 1));
var second = int.Parse(attribute.Name.Substring(1));
var third = int.Parse(attribute.Name.Substring(2));
Alternatively, you could use the Type.GetGenericTypeDefinition() method to get the type of the attribute and then use the Type.GetGenericArguments() method to get the type's arguments.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KarlH |
| Solution 2 | Jason Malinowski |
| Solution 3 | Pascal Arsenal |
