如何横盒UIButtons?

时间:2016-01-22 07:19:14

标签: xcode swift

我需要创建一个视图,其中要显示的按钮数量取决于init的参数。我怎样才能使水平盒UIButtons成为可能?

    override func viewDidLoad() {
    var bs = 0;
   for index in 1...20
   {
        bs+=50;var x = CGFloat(bs)
        let button   = UIButton(type: UIButtonType.System) as UIButton
        button.contentMode = UIViewContentMode.ScaleToFill
        button.frame = CGRectMake(x, 50, 40, 40) // X, Y, width, height
        button.backgroundColor = UIColor.whiteColor()
        button.setTitle("12", forState: UIControlState.Normal)
        button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(button);
        }
       }

i want to like this

我想要这样

1 个答案:

答案 0 :(得分:1)

您应该查看UICollectionView

如果您不想使用UICollectionView,我会为您提供这个小样本,无论是使用UIView还是UIScrollView,都可以尝试构建它:


let view = UIView(frame: CGRect(origin: CGPointZero, size: CGSize(width: 300, height: 300)))
view.backgroundColor = UIColor.redColor()

let buttonHeight = 40
let buttonWidth = 40
let marginInterCell = 10
let marginInterRow = 20

let numberOfButtonsInRow = 300/(buttonWidth + marginInterCell)
let totalNumberOfButtons = 20

for index in 0..totalNumberOfButtons {
    let button  = UIButton(type: UIButtonType.System) as UIButton
    button.titleLabel?.text = "\(index)"
    let x = (index % numberOfButtonsInRow) * (buttonWidth + marginInterCell) + marginInterCell/2
    let y = (buttonHeight + marginInterRow) * (index / numberOfButtonsInRow) + marginInterRow/2
    button.backgroundColor = UIColor.greenColor()
    button.frame = CGRect(origin: CGPoint(x: x, y: y), size: CGSize(width: buttonWidth, height: buttonHeight))
    view.addSubview(button)
}