我有一個UISwitch
,它包含在原型單元中,該原型單元是UITableViewCell
的子類。這個原型單元格包含一個UISwitch
,當應用程序最初啓動時,我希望將其初始狀態設置爲false,以及每當用戶更改時希望存儲哪個狀態。我的問題是試圖從UITableViewController
中獲得對UISwitch
的引用,此時UISwitch
包含在原型單元內。嘗試在Swift中設置UISwitch的初始狀態
這裏是我的相關代碼:
裏面我AppDelegate
我有以下幾點:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if !NSUserDefaults.standardUserDefaults().boolForKey("isNotFirstLaunch") {
//Set switchState to false and isNotFirstLaunch to true
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "switchState")
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isNotFirstLaunch")
//Sync NSUserDefaults
NSUserDefaults.standardUserDefaults().synchronize()
}
裏面我UITableViewController
:
override func viewDidLoad() {
//this line below is commented out because I don't have a reference to the UISwitch in question, but I imagine it would be something along these lines:
//switchState.on = NSUserDefaults.standardUserDefaults().boolForKey("switchState")
}
//This block of code I was able to connect to the UISwitch directly in the storyboard file, so I know this works.
@IBAction func stateChanged(withSwitchState switchState: UISwitch) {
if switchState.on {
NSUserDefaults.standardUserDefaults().setBool(switchState.on, forKey: "switchState")
} else {
NSUserDefaults.standardUserDefaults().setBool(switchState.on, forKey: "switchState")
}
}
而且我班爲原型細胞內:
class SwitchTableViewCell: UITableViewCell {
@IBOutlet weak var switchControl: UISwitch!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.switchControl.layer.cornerRadius = 16
}
}
我需要對原型單元格內的UISwitch
的引用,它在我的UITableViewController
類中,使得它的初始狀態設置爲false,如我的AppDelegate
類中所建立的,並且每當用戶更改UISwitch
的狀態。
設置狀態在cellforrow方法 –
如何內我在「cellForRowAtIndexPath」中獲得對自定義單元類的引用嗎?當我這樣做: 如果單元格是SwitchTableViewCell { ... } 我無法使用「單元格」來獲取其類中的UISwitch參數的引用。 – syedfa
@syedfa檢查我的答案,以獲得對你的牢房的重視。 –