【问题标题】:I am interested in accessing the uibutton method from external method but I'm getting lot of errors我有兴趣从外部方法访问 uibutton 方法,但我遇到了很多错误
【发布时间】:2017-07-18 06:34:10
【问题描述】:

下面是我的代码。我的视图中有 9 个按钮要更改其背景图像。

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

【问题讨论】:

  • 你在哪里添加这 9 个按钮?
  • 有什么错误?是什么线导致它们?请edit您的问题提供这些详细信息。
  • 我正在尝试访问下面代码中的按钮.. 让 newButton = self.view.viewWithTag(i) as! UIButton newButton.setBackgroundImage(UIImage.init(named: ""), for: .normal)
  • 你想做什么,你面临的问题是什么?还是不清楚你的问题
  • 你是在 xib 还是 storyboard 中添加按钮?

标签: ios swift


【解决方案1】:

您需要向 UIAlertController 添加操作。在定义 action1 后添加以下行:

[alerts addAction: action1]

【讨论】:

    【解决方案2】:

    试试这个:

    首先将按钮添加到视图并为其添加操作:

    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:)
        }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      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;
          }
      

      【讨论】:

      • 你能帮我找到,如何从 IB 函数以外的函数中指向新的按钮变量(它已经在故事板中用特定的标签创建)
      • if currentSymbol == 1 { sender .setBackgroundImage(UIImage(named: "cross.png"), for: UIControlState()) currentState[sender.tag] = 1 currentSymbol = 2 } else if currentSymbol == 2 { sender.setBackgroundImage(UIImage(named: "nought.png"), for: UIControlState()) currentState[sender.tag] = 2 currentSymbol = 1 }
      • 这是我用来在点击时更改背景图像的代码..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2019-07-22
      • 2012-04-12
      • 1970-01-01
      • 2011-04-12
      相关资源
      最近更新 更多