Home > Net >  Problem with offset and buttons in SwiftUI?
Problem with offset and buttons in SwiftUI?

Time:07-26

I have a group of buttons that i show with a clockwise rotation, but I cannot click them properly:

I think there is a problem with the offset but I don't know how to solve it, any suggestions?

This is the code:

struct CategoryView: View {
    // Circle Radius
    @State private var radius: Double = 150
    let circleSize: Double = 350
    // Degree of circle
    @State private var degree = -90.0
    let cards = ["John", "Mark", "Alex", "Kevin", "Jimmy"]
    
    var body: some View {
        ZStack {
            let anglePerCount = Double.pi * 2.0 / Double(cards.count)
            ForEach(0..<cards.count, id: \.self) { index in
                let angle = Double(index) * anglePerCount
                let xOffset = CGFloat(radius * cos(angle))
                let yOffset = CGFloat(radius * sin(angle))
                Button {
                    
                } label: {
                Text(cards[index])
                    .font(.title)
                    .fontWeight(.bold)
                    .rotationEffect(Angle(radians: angle   Double.pi/2))
                    .offset(x: xOffset, y: yOffset)
                }
            }
        }
        .rotationEffect(Angle(degrees: degree))
        .onAppear() {
            radius = circleSize/2 - 47 // 47 is for padding
        }
    }
}

CodePudding user response:

This is a simple mistake, that all SwiftUI devs have made countless times. You're modifying the label, but not the actual button itself. Simply move the modifier to the Button.

Button (action: {}, label: {
            Text(cards[index])
                .font(.title)
                .fontWeight(.bold)
            })
             .rotationEffect(Angle(radians: angle   Double.pi/2))
             .offset(x: xOffset, y: yOffset)

In SwiftUI nearly everything is a View and can be treated as such. A button, also a view, can have most of the same modifiers that a Text can have. In your question, you made a change to the inner view of the button, and not the actual button itself. That's why when you were clicking in the middle, it appeared to not be positioned right, but in fact it did exactly what you told it too. That is an important thing to remember because you can actually push, pull, and offset things outside of the view which makes for some interesting layouts; Layouts such as side-menus, or modals.

  • Related