[英]How to call UISwitch declared in Custom Cell in Table View ViewDidLoad method ?
我有一個帶有UILabel
和UISwitch
的自定義Cell的TableView
。 UISwitch在Custom Cell中聲明。 我想在TableView的ViewDidLoad
中調用此開關。 我想使用NSUserDefaults
來保存UISwitch的狀態。 要加載值,我必須在ViewDidLoad中編寫代碼。
@interface LabelSwitchCustomCell : UITableViewCell {
IBOutlet UILabel *mainLabel;
IBOutlet UISwitch *switchButton;
}
@property (nonatomic, retain) IBOutlet UILabel *mainLabel;
@property (nonatomic, retain) IBOutlet UISwitch *switchButton;
@end
您可以從代碼中的任何位置在NSUserDefaults中保存UISwitch的狀態。 您可以這樣設置/加載開關狀態:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Set switch states
if (indexPath.row == 0)
cell.switchBtn.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"Switch1State"];
else if(indexPath.row == 1)
cell.switchBtn.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"Switch2State"];
else if(indexPath.row == 2)
cell.switchBtn.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"Switch3State"];
// Set switch states
// Set action for your switch
[cell.switchBtn addTarget:self action:@selector(switchingBtn:) forControlEvents:UIControlEventValueChanged];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexpath
{
LabelSwitchCustomCell *switchCell = (LabelSwitchCustomCell *)[tableView dequeueReusableCellWithIdentifier:@"YOUR_CELL_IDENTIFIER"];
switchCell.switchButton.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"SwitchState"];
}
然后,在Interface Builder中,使用在自定義單元類中聲明並實現的此操作連接交換機:
- (IBAction)switchFlipped:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:self.switchButton.on forKey:@"SwitchState"];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.