我一直在努力在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)
}
答案 0 :(得分:1)
let gap: CGFloat = 0
如果您要留空白,那就错了。不应该是... = 15
?
替代方案可以包括将它们放置在spacing
集的UIStackView中。使用自动布局,在提供间隙的按钮之间创建约束,这也将很简单。
答案 1 :(得分:0)
另一个建议:
我建议使用UIStackView
以获得所需的外观,而不是直接在滚动视图中添加按钮。 gap
将表示为spacing
属性。
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.distribution = .equalSpacing
// here is the "gap":
stackView.spacing = 16.0
因此,您应该在其中添加按钮:
stackView.addArrangedSubview(button)