我正在尝试将多个按钮添加到水平滚动UIScrollView
中。目前,我在按UIScrollView
。
我想达到以下效果:
我想我最好的选择是在按钮上添加AutoLayout。这个上有什么线索吗?
以下是与此问题相关的代码:
class SeasonNavigatorScrollView: UIScrollView {
private let kButtonSize:CGFloat = 50.0
private let kSpacing:CGFloat = 10.0
private var buttons:[UIButton] = []
var seasonNavigatorDelegate:SeasonNavigatorDelegate?
func setup(count:Int) {
self.contentSize = CGSizeMake((kButtonSize+kSpacing)*CGFloat(count), self.bounds.size.height)
for i in 0..<count {
let button = UIButton(type: .Custom)
button.setTitle("\(i+1)", forState:.Normal)
button.setTitleColor(.whiteColor(), forState: .Normal)
button.tag = i
button.layer.cornerRadius = kButtonSize/2
button.frame = CGRectMake((kButtonSize+kSpacing)*CGFloat(i), 0, kButtonSize, kButtonSize)
button.backgroundColor = UIColor.clearColor()
button.addTarget(self, action: "didClickSeason:", forControlEvents: .TouchUpInside)
buttons.append(button)
self.addSubview(button)
}
if count > 0 {
self.animateButtonSelection(buttons[0])
}
}
}
修改 这里有一些图片可能会澄清我在寻找的东西:
1
2
多个:
谢谢, 大卫
编辑2: 首先感谢@OmkarGuhilot解决方案部分适用于我,但是当我添加更多按钮而不是适合我的self.view.bounds时,我遇到了问题。然后,FlowLayout子类将构成第二行,而不是提供水平滚动的可能性。
这是我的解决方案按预期工作:
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: Int) -> UIEdgeInsets {
let totalCellWidth:CGFloat = 50.0 * CGFloat(self.seasons.count)
let viewWidth:CGFloat = self.seasonNavigator.bounds.size.width
let totalSpacingWidth:CGFloat = 10 * (CGFloat(self.seasons.count)-1)
print(viewWidth)
let leftInsets = (viewWidth - (totalCellWidth + totalSpacingWidth)) / 2
let rightInsets = leftInsets
return UIEdgeInsetsMake(0, max(leftInsets,10), 0, max(rightInsets,10))
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
self.seasonNavigator.collectionViewLayout.invalidateLayout()
}
答案 0 :(得分:1)
答案 1 :(得分:0)