2016-01-22 59 views
0

我需要製作一個視圖,其中要顯示的按鈕數量取決於init的參數。我怎樣才能使水平框UIButtons成爲可能?如何水平框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

我想喜歡這個

+0

沒有。但我不想在我的項目中使用UICollectionView。請給我水獺選項嗎? – Darkface35

+0

如果你不想使用集合視圖,而不是唯一的選擇是在Scrollview中添加這個 – Mayur

回答

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) 
} 
+0

我知道如何使用UICollectionView,但在我的項目中,我必須使用view.addSubview.So你能幫我view.addSubview嗎? – Darkface35