我正在处理我的第一个个人应用程序我需要一些关于如何以编程方式创建Switch以显示在我的自定义单元格内(在每个标签的右侧)的指导。
请注意,我非常确定我已经不正确地实施了切换,因为用户无法实际与其进行交互,但是我的主要问题在标题中说明,答案并不一定需要解决这个问题。
话虽如此,对这两点中的任何一点的任何指导都将不胜感激。
谢谢!
SettingsItem.swift
class SettingsSwitch {
var label : String = "Label"
var active : Bool = false
init(label: String, active: Bool) {
self.label = label
self.active = active
}
}
SettingCell.swift
class SettingCell: UITableViewCell {
@IBOutlet var settingsLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
//MARK: - custom
func setCell(labelText: String, activeBool: Bool) {
self.settingsLabel.text = labelText
var newSwitch = UISwitch(frame:CGRectMake(150, 300, 0, 0))
newSwitch.on = activeBool
newSwitch.setOn(activeBool, animated: true)
addSubview(newSwitch)
}
}
TableViewController.swift
class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var settings : [SettingsSwitch] = [SettingsSwitch]()
@IBOutlet var settingsTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.initializeSettings()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return settings.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : SettingCell = tableView.dequeueReusableCellWithIdentifier("Cell") as SettingCell
let settingMenu = settings[indexPath.row]
cell.setCell(settingMenu.label, activeBool: settingMenu.active)
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidAppear(animated: Bool) {
settingsTable.reloadData()
}
// MARK: - custom functions
func initializeSettings() {
var coolDownOption = SettingsSwitch(label: "Cool Down Timer", active: false)
var useDefaultTimes = SettingsSwitch(label: "Use Default Times", active: true)
settings.append(coolDownOption)
settings.append(useDefaultTimes)
}
}
答案 0 :(得分:1)
试试这个:
class SettingCell: UITableViewCell {
@IBOutlet var settingsLabel: UILabel!
var newSwitch: UISwitch!
override func awakeFromNib() {
super.awakeFromNib()
//The rect does not seems to be correct. This will go way beyond the cell rect.
//may be use UISwitch(frame:CGRectMake(150, 10, 0, 0))
newSwitch = UISwitch(frame:CGRectMake(150, 300, 0, 0))
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
//MARK: - custom
func setCell(labelText: String, activeBool: Bool) {
self.settingsLabel.text = labelText
newSwitch.on = activeBool
newSwitch.setOn(activeBool, animated: true)
//Add to contentView instead of self.
contentView.addSubview(newSwitch)
}
}
我不确定你为什么不把UISwitch放在xib中。如果在setCell中创建UISwitch,则会在重用单元格时多次创建它。所以最好在awakefromNib()中创建它。
使用自动布局而不是设置固定矩形也是一个更好的主意。