2017-02-14 104 views
1

我想添加功能動態創建按鈕。我已經創建了功能按鈕,但從未編程過。這是我的代碼。添加功能,以編程方式創建的UIButtons

let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in 
     if error != nil 
     { 
      print("error") 
     } 
     else 
     { 
      if let content = data 
      { 
       do 
       { 
        //download JSON data from php page, display data 
        let SongArray = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! [[String]] 
        print(SongArray) 

        //Make buttons with JSON array 
        var buttonY: CGFloat = 20 
        for song in SongArray { 
         let songButton = UIButton(frame: CGRect(x: 50, y: buttonY, width: 250, height: 30)) 
         buttonY = buttonY + 50 // 50px spacing 

         songButton.layer.cornerRadius = 10 //Edge formatting for buttons 

         songButton.backgroundColor = UIColor.darkGray //Color for buttons 

         songButton.setTitle("\(song[0])", for: UIControlState.normal) //button title 

         songButton.titleLabel?.text = "\(song[0])" 

         songButton.addTarget(self,action: #selector(self.songButtonPressed(_:)), for: .touchUpInside) 
         DispatchQueue.main.async { 
          self.view.addSubview(songButton) // adds buttons to view 
         } 
        } 
       } 
       catch 
       { 

       } 
      } 
     } 
    } 
    task.resume() 

} 

} //close viewDidLoad 
func songButtonPressed(_ sender:UIButton) { // function for buttons 

if sender.titleLabel?.text == "\("Song[0]")" { 
    print("So far so good!!") 
} 
} 

我非常想要做的就是使用功能SongButtonPressed當任一按鈕被按下運行,到目前爲止,當我點擊一個按鈕,雖然他們出現就好了應用程序只是崩潰。如何使用函數替換下面一行將功能添加到這些按鈕動態

+1

碰到什麼錯誤? – Carcigenicate

+1

如果您希望'SongButtonPressed'運行,請將其用作選擇器。 –

+0

'libC++ abi.dylib:終止於類型爲NSException的未捕獲異常' – xteetsx

回答

0

嘗試: 函數名必須出現在選擇屬性

SongButton.addTarget(自我,動作:#selector(個體經營。 SongButtonPressed(_ :)),用於:UIControlEvents.touchUpInside)

而且最重要的功能SongButtonPressed必須viewDidLoad中

+0

在該行上拋出一個錯誤,表示'不能轉換類型的值'(UIbutton) - >( )'到期望的參數類型'String' – xteetsx

+0

嘗試更新的代碼行@xteetsx –

0

看起來你正在使用的UIKit框架,這樣你就可以使用.isHidden方法或.isEnabled

隱藏方法隱藏按鈕和啓用的方法將出現按鈕,但用戶將無法按下按鈕。

要使用該方法寫下面的代碼。

Button.isHidden = true 

或者

Button.is enabled = false 

但是如果你使用這些方法,你需要有一個按鈕,會得到相反效果(將其設置爲true,如果是假的還是假的,如果它是真實的),這樣該按鈕可以再次使用。

相關問題