'cornerRadius on message SwiftUI
I'm having this problem that my messages don't have corner radius on the other side. This is how it looks:
And there is the code for it:
HStack {
HStack {
Text(text)
.fixedSize(horizontal: false, vertical: true)
.foregroundColor(isSender ? Color.white : Color(.label))
.padding()
}
.background(isSender ? Color.blue : Color(.systemGray5))
.padding(isSender ? .leading : .trailing,
isSender ? UIScreen.main.bounds.width*0.28 : UIScreen.main.bounds.width*0.2)
}
.cornerRadius(10)
How do I make it rounded on the other side too?
Solution 1:[1]
Actually what you're doing is applying padding after the background, in this way your padding will apply to your background view and now your background view is no more on the corner that's why no round corner on specific side, you can place padding before the background to achieve what you're looking for:
HStack {
HStack {
Text(text)
.fixedSize(horizontal: false, vertical: true)
.foregroundColor(isSender ? Color.white : Color(.label))
.padding()
}
.padding(isSender ? .leading : .trailing,
isSender ? UIScreen.main.bounds.width*0.28 : UIScreen.main.bounds.width*0.2) //HERE
.background(isSender ? Color.blue : Color(.systemGray5))
}
.cornerRadius(10)
Also you can achieve round corners for your existing code but just shifting cornerRadius from HStack to your background view like this:
HStack {
HStack {
Text("text")
.fixedSize(horizontal: false, vertical: true)
.foregroundColor(isSender ? Color.white : Color(.label))
.padding()
}
.background(isSender ? Color.blue : Color(.systemGray5))
.cornerRadius(10) //HERE
.padding(isSender ? .leading : .trailing,
isSender ? UIScreen.main.bounds.width*0.28 : UIScreen.main.bounds.width*0.2)
}
Solution 2:[2]
The ordering of modifiers is important.
You are first applying padding, then cornerRadius. This gives the (invisible) padding a rounded corner. If you do it the other way round – first cornerRadius then padding – it works:
HStack {
Text(text)
.fixedSize(horizontal: false, vertical: true)
.foregroundColor(isSender ? Color.white : Color(.label))
.padding()
}
.background(isSender ? Color.blue : Color(.systemGray5))
.cornerRadius(10) // << first radius, then padding
.padding(isSender ? .leading : .trailing,
isSender ? UIScreen.main.bounds.width*0.28 : UIScreen.main.bounds.width*0.2)
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 | Umair Khan |
Solution 2 | ChrisR |