Simplest way to evenly distribute UIButtons horizontally across width of view controller?

前端 未结 8 770
挽巷
挽巷 2021-02-01 07:48

I\'ve looked through many answers and they all seem very complex! Most recently I was looking at this answer although I\'d prefer not to have to put my buttons inside views.

相关标签:
8条回答
  • 2021-02-01 08:18

    I usually do something like:

    int numButtons = 6;
    float gap = 10.0f;
    float y = 50.0f;
    float width = (self.view.frame.size.width - gap * (numButtons + 1)) / numButtons;
    float height = 60.0f;
    for (int n=0;n<numButtons;n++) {
        float x = gap * (n+1) + width * n;
        UIButton *button = [self.buttons objectAtIndex:n]; //Or get button some other way/make button.
        [button setFrame:CGRectMake(x,y,width,height)];
    }
    

    You can set numButtons to however many buttons you want in the row, and if you have an array of buttons, you can set it to the length of that array.

    The y is just whatever y coordinate you want and the same goes for the height and gap, which is the space between buttons. The width is just a calculation of how wide each button will be based on the screen width and the gap space you want between each button.

    0 讨论(0)
  • 2021-02-01 08:18

    I just cooked this up in Swift using Cartography.

    func disributeEvenlyAcrossWithCartography(views: [UIView], enclosingBox: UIView, spacer: CGFloat = 10.0) {
        var priorView = UIView() // never null
        for (index, view) in views.enumerate() {
            constrain(view, priorView, enclosingBox) { view, prior, enclosingBox in
                view.height == enclosingBox.height
                view.centerY == enclosingBox.centerY
                if index == 0 {
                    view.width == enclosingBox.width / CGFloat(views.count) - spacer
                    view.left == enclosingBox.left
                } else {
                    view.left == prior.right + (spacer + spacer / CGFloat(views.count - 1))
                    view.width == prior.width
                }
            }
            priorView = view
        }
    }
    

    Result with 5 views and a small spacer:

    0 讨论(0)
提交回复
热议问题