我创建了一个表,其中每一行都有一个名称和一个 UISwitch 按钮。行数不固定(因此 UI 开关的数量也不固定),它取决于用户输入。 我已经设法给每个 UISwitch 一个标签,但我不知道如何从 @IBAction 函数访问它们
代码
import UIKit
class Katw2ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var perasmenoList = [String]()
var listaApotelesmatwn = [String]()
@IBOutlet weak var katw2Tableview: UITableView!
@IBOutlet weak var debugLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.katw2Tableview.dataSource = self
self.katw2Tableview.delegate = self
// Do any additional setup after loading the view.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return perasmenoList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
var switchView = UISwitch()
cell.accessoryView = switchView
switchView.tag = indexPath.row
switchView.addTarget(self, action: Selector("switchChanged"), forControlEvents: UIControlEvents.ValueChanged)
cell.textLabel!.text = self.perasmenoList[indexPath.row]
return cell
}
@IBAction func switchChanged(sender: UISwitch) {
//Do things
}
}
最佳答案
从我刚刚从 nhgrif 的链接中找到的另一篇文章中,所缺少的只是“switchChanged:”中的一个分号
switchView.addTarget(self, action: #selector(PIN.switchChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)
现在可以了
关于Swift:如何访问仅使用一个函数以编程方式创建的多个 UISwitch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30050473/