我非常努力地在 UIScrollView 中的按钮数组之间添加空间,但我做不到。有什么办法可以在 UIScrollView 中的按钮数组之间留出空间吗? 我附上了一张图片,解释了我想要什么。
这是我的代码:
//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/