Faris
Faris

Reputation: 1236

How to add space between buttons in uiscrollview

I was trying so hard to add space between buttons array in UIScrollView but I couldn't make it. There is any way to make space between buttons array in UIScrollView ? I have attached a picture explaining what I want.

enter image description here

This is my code :

 //MARK: - SETUP CATEGORIES BUTTONS
func setupCategoriesButtons() {
    var xCoord: CGFloat = 1
    let yCoord: CGFloat = 1
    let buttonHeight: CGFloat = 40
    let buttonwidth: CGFloat = 40
    let gap: CGFloat = 0


    // Counter for items
    var itemCount = 0

    // Loop for creating buttons
    for i in 0..<myArray.count {
        itemCount = i

        // Create a Button
        let catButt = UIButton(type: .custom)


        catButt.showsTouchWhenHighlighted = true
        catButt.setTitle("\(myArray[itemCount])", for: .normal)
        catButt.sizeToFit()


        catButt.frame = CGRect(x: xCoord, y: yCoord, width: catButt.frame.size.width + 30, height: buttonHeight)

        catButt.layer.cornerRadius = 8

        catButt.titleLabel?.font = UIFont(name: "Titillium-Semibold", size: 12)
      //  catButt.addTarget(self, action: #selector(categoryButt(_:)), for: UIControlEvents.touchUpInside)

        // Add Buttons & Labels based on xCood
        xCoord +=  catButt.frame.size.width + gap
        categoriesScrollView.addSubview(catButt)
        letterButtons.append(catButt)
    } // END LOOP --------------------------

    for i in 0..<letterButtons.count {
        letterButtons[i].tag = i
        letterButtons[i].backgroundColor = RandomColor()
        letterButtons[i].setTitleColor(UIColor.white, for: .normal)
    }

    // Place Buttons into the ScrollView
    categoriesScrollView.contentSize = CGSize(width: buttonwidth * CGFloat(itemCount+1), height: yCoord)
}

Upvotes: 0

Views: 331

Answers (2)

Ahmad F
Ahmad F

Reputation: 31645

Another suggestion:

I would suggest to use a UIStackView for achieving the desired appearance instead of adding the buttons directly in the scroll view. The gap would be represented as spacing property.

let stackView = UIStackView()
stackView.axis = .horizontal
stackView.distribution = .equalSpacing
// here is the "gap":
stackView.spacing   = 16.0

therefore, you should add the buttons in it:

stackView.addArrangedSubview(button)

Upvotes: 0

Graham Perks
Graham Perks

Reputation: 23390

let gap: CGFloat = 0

Looks wrong, if you want a gap. Shouldn't it be e.g. ... = 15?

Alternatives could include placing them in a UIStackView with a spacing set. This would also be simple using auto-layout, creating constraints between the buttons which provide the gaps.

Upvotes: 1

Related Questions