2017-07-18 38 views
-3

以下是我的代碼。我的視圖中有9個按鈕,其背景圖像將被更改。奧瑞克幫助我。我intrested從外部方法訪問uibutton方法,但我得到很多錯誤

import UIKit 

class ViewController: UIViewController { 
    let alerts = UIAlertController(title: "Hi", message: "Hello", preferredStyle: UIAlertControllerStyle.alert) 

    let action1 = UIAlertAction(title: "Yes", style: UIAlertActionStyle.default) { (<#UIAlertAction#>) in 
     for i in 0..<9 
     { 
      let newButton = self.view.viewWithTag(i) as! UIButton 
      newButton.setBackgroundImage(UIImage.init(named: ""), for: .normal) 
     } 
    } 

    @IBAction func buttonPressed(_ sender: UIButton) 
    { 
     sender.setBackgroundImage(UIImage.init(named: "cross.png"), for:.normal) 
    } 
} 
+0

在其中添加的9個按鍵? – Venkat

+0

有什麼錯誤?什麼線路導致他們?請用這些細節編輯你的問題。 – rmaddy

+0

我想要訪問波紋管代碼中的按鈕..讓newButton = self.view.viewWithTag(i)as! UIButton newButton.setBackgroundImage(UIImage.init(named:「」),for:.normal) –

回答

0

試試這個:

newButton .setBackgroundImage(UIImage.init(named: ""), for: .normal) 
newButton .setBackgroundImage(UIImage.init(named: "cross.png"), for: .selected) 

@IBAction func buttonPressed(_ sender: UIButton) 
    { 
     sender.isSelected = !sender.isSelected; 
    } 
+0

你能幫我找出如何從IB函數以外的函數中指出新的按鈕變量(它已經在具有特定標籤的故事板中創建) –

+0

if currentSymbol == 1 { 發件人.setBackgroundImage(的UIImage(命名爲: 「cross.png」),用於:UIControlState()) currentState [sender.tag] = 1 currentSymbol = 2 } 否則如果currentSymbol == 2 { 發件人。 setBackgroundImage(UIImage(named:「nought.png」),用於:UIControlState()) currentState [sender.tag] = 2 currentSymbol = 1 } –

+0

這是我用來更改點擊背景圖片時的代碼.. –

0

您需要添加動作UIAlertController。添加以下行定義動作1後:

[alerts addAction: action1] 
0

試試這個:

首先添加按鈕,查看併爲其添加動作:

for i in 0..<9 
    { 
      let newButton = UIButton(frame : yourFrame) 
      newButton.setBackgroundImage(UIImage.init(named: ""), for: .normal) 
      newButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) 
      newbutton.tag = i 
      self.view.addSubview(newButton:) 
    } 
相關問題