[objective-c] iOS-프로그래밍 방식으로 UISwitch를 설정하는 방법

프로그래밍 방식으로 UISwitch를 켜거나 끄고 싶습니다. 어떻게할까요? 저는 iOS 초보자입니다.



답변

UISwitch를 사용하는 경우 개발자 API에서 볼 수 있듯이 작업 setOn: animated:이 트릭을 수행해야합니다.

- (void)setOn:(BOOL)on animated:(BOOL)animated

따라서 프로그램에서 스위치를 ON으로 설정하려면 다음을 사용합니다.

목표 -C

[switchName setOn:YES animated:YES];

빠른

switchName.setOn(true, animated: true)


답변

UISwitch에는 설정해야하는 “on”이라는 속성이 있습니다.

iOS 앱 또는 모바일 웹 사이트에 대해 이야기하고 있습니까?


답변

이 코드를 사용하여 iOS의 스위치에서 켜짐 / 꺼짐 상태 문제를 해결하십시오.

- (IBAction)btnSwitched:(id)sender {
    UISwitch *switchObject = (UISwitch *)sender;
    if(switchObject.isOn){
        self.lblShow.text=@"Switch State is Disabled";
    }else{
        self.lblShow.text=@"Switch State is Enabled";
    }                


답변

나는 또한 setOn:animated:이것을 사용하고 잘 작동합니다. 이것은 프리셋을로드하도록 인 코드 viewDidLoad를 토글하기 위해 앱에서 사용하는 코드 UISwitch입니다.

// Check the status of the autoPlaySetting
BOOL autoPlayOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"autoPlay"];

[self.autoplaySwitch setOn:autoPlayOn animated:NO];


답변

ViewController.h

- (IBAction)switchAction:(id)sender;
@property (strong, nonatomic) IBOutlet UILabel *lbl;

ViewController.m

- (IBAction)switchAction:(id)sender {

    UISwitch *mySwitch = (UISwitch *)sender;

    if ([mySwitch isOn]) {
        self.lbl.backgroundColor = [UIColor redColor];
    } else {
        self.lbl.backgroundColor = [UIColor blueColor];
    }
}


답변