2017-06-28 6 views
0
func addStartingButtons2() { 

     let button = UIButton(frame: CGRect(x: 50, y: buttonY, width: 250, height: 30)) 

     button.layer.cornerRadius = 10 // get some fancy pantsy rounding 
     button.backgroundColor = UIColor.darkGray 
     button.setTitle("Button for Villain: \(String(describing: hashes[button]))", for: UIControlState.normal) 

     buttons.append(button) 
     buttons.append(button) 

     for button in buttons { 
      self.view.addSubview(button) 
      button.frame.origin.y += 50 
     } 
    } 

に追加します。 var hashes = [UIButton : [Double]]() var buttons = [UIButton]()配列は、ビュー

は、この関数に2と同じボタン他onder 1を追加したいのですが、一つだけのボタンは

答えて

0

ええ、同じボタンを2回追加しようとしています。

私はコードをテストしませんでしたが、ロジックをforループに入れ、ボタンの間に少しのパディングを追加することでこれを行うことができます。そうしないと、オーバーラップします。

このような何か:

func addStartingButtons2() { 

    for villain in villains { // this depends on your needs, it's just an example 

     let button = UIButton(frame: CGRect(x: 50, y: buttonY, width: 250, height: 30)) 

     // Add offset for the next button. 
     buttonY += 40 

     button.layer.cornerRadius = 10 // get some fancy pantsy rounding 
     button.backgroundColor = UIColor.darkGray 
     button.setTitle("Button for Villain: \(String(describing: hashes[button]))", for: UIControlState.normal) 

     buttons.append(button) 
    } 

    for button in buttons { 
     self.view.addSubview(button) 
     button.frame.origin.y += 50 
    } 

    // If you want to avoid the second loop 
    // you can just put view.addSubview(button) inside the first for loop 
} 
0

これは動作しません実現しています。あなたの配列buttonsはあなたのボタンのリファレンスを格納しているので、実際には2つのリファレンスを配列に入れています。

自分で結果を確認するには、ループ内にブレークポイントを置くと、同じアドレスのボタンが2回表示されます。

enter image description here

あなたは複数のボタンを持っているしたい場合は、それらを一つずつ作成する必要があります。

関連する問題