swift - 如何在 uiscrollview 中的按钮之间添加空间

标签 swift

我非常努力地在 UIScrollView 中的按钮数组之间添加空间,但我做不到。有什么办法可以在 UIScrollView 中的按钮数组之间留出空间吗? 我附上了一张图片,解释了我想要什么。

enter image description here

这是我的代码:

 //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)
}

最佳答案

let gap: CGFloat = 0

看起来不对,如果你想要一个差距。不应该是例如... = 15?

备选方案可能包括将它们放置在具有 spacing 集的 UIStackView 中。使用自动布局也很简单,在提供间隙的按钮之间创建约束。

关于swift - 如何在 uiscrollview 中的按钮之间添加空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52281195/

相关文章:

swift - 如何在不创建新记录的情况下更新cloudKit上的数据?

ios - 将 iAd 设置在屏幕顶部

swift - GetStream EnrichedActivity 类的复制问题

ios - 如何对拼接图像进行动画处理?

swift - 转换为字符串任意值

php - 如何在 swift 中 http 发布特殊字符

xcode - Swift 2 中的 do-try-catch 用法

ios - 如何根据字符串大小在 UITableViewCell 中动态设置 UITextView 的高度?

ios - 如何在 iOS 或 OS X 下使用 Swift 的 Activity Trace

swift - 如何使用 Swift 检索地址簿联系人?