UITableViewCell
의 하위 클래스 인 Prototype 셀 안에 포함 된 UISwitch
이 있습니다. 이 프로토 타입 셀은 UISwitch
을 포함합니다. 초기 상태는 앱이 처음 시작될 때 false로 설정하고 사용자가 변경할 때마다 상태를 저장하려고합니다. 제 문제는 UISwitch
이 프로토 타입 셀 안에 포함되어있을 때 UITableViewController
에서 UISwitch
에 대한 참조를 얻으려고합니다. 나는 다음과 같은이 내 AppDelegate
내부Swift에서 UISwitch의 초기 상태 설정 시도
: 여기
내 관련 코드 내부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
}
}
내 UITableViewController
클래스 내 프로토 타입 셀 안에 들어있는 UISwitch
에 대한 참조가 필요합니다. 즉, 내 AppDelegate
클래스에 설정된대로 초기 상태가 false로 설정되며, 사용자가 해당 셀을 변경할 때마다 앞으로 상태가 유지됩니다. UISwitch
의 상태. 스토리 보드에서
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as SwitchTableViewCell
if !NSUserDefaults.standardUserDefaults().objectForKey("switchState")
{
cell. switchControl.setOn(true, animated: true)
}
else
{
cell. switchControl.setOn(false, animated: true)
}
cell. switchControl.tag = indexPath.row
cell. switchControl.addTarget(self, action: "switchChanged:", forControlEvents: UIControlEvents.ValueChanged)
return cell
}
func switchChanged(mySwitch: UISwitch) {
if switchState.on {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "switchState")
} else {
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "switchState")
}
self.tableview.reloadData()
}
처럼 swicth가 cellforrow 방법 –
어떻게 내부 상태를 설정에 액세스 할 수 있습니다 "cellForRowAtIndexPath"내부의 사용자 정의 셀 클래스에 대한 참조를 가져 옵니까?나는이 수행 할 때 셀 SwitchTableViewCell 경우 을 { ... } 나는 그것의 클래스 내부의 UISwitch 매개 변수에 대한 참조를 얻기 위해 "세포"를 사용할 수 없습니다입니다. – syedfa
@syedfa 내 대답을 확인하여 셀에 대한 정보를 얻으십시오. –