根据UISwitch.on,UITextField.enabled为Yes或No

时间:2014-04-13 13:05:36

标签: ios objective-c uitextfield uiswitch

我想让textField.enabled开启和关闭 但无论textField如何,switch.on都无法修改 我该如何解决?

UISwitch* switch = [[UISwitch alloc]initWithFrame:CGRectMake(140, 293, 60, 25)];
[self.view addSubview:switch];

UITextField* textField = [[UITextField alloc]initWithFrame:CGRectMake(200, 293, 100, 30)];
textField.delegate = self;
[self.view addSubview:textField];

if (switch.on == YES) {
    textField.enabled = YES;
} else {
    textField.enabled = NO;
}

谢谢。

3 个答案:

答案 0 :(得分:3)

您需要将目标添加到UISwitch

-(void)viewDidLoad
{
    [super viewDidLoad];

    UISwitch* switch = [[UISwitch alloc]initWithFrame:CGRectMake(140, 293, 60, 25)];
    [switch addTarget:self action:@selector(didChangeSwitch:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:switch];

    UITextField* textField = [[UITextField alloc]initWithFrame:CGRectMake(200, 293, 100, 30)];
    textField.delegate = self;
    [self.view addSubview:textField];
    self.textField = textField;

}

-(void)didChangeSwitch:(UISwitch *)sender
{ 
    self.textField.enabled = switch.on;
}

答案 1 :(得分:1)

顺便说一下,你可以替换

if (switch.on == YES) {
    textField.enabled = YES;
} else {
    textField.enabled = NO;
}

textField.enabled=switch.on;

<小时/> 另一种方法是创建计时器:

NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:0.1
    target:self selector:@selector(yourSelector:) userInfo:nil repeats:YES];

声明选择器:

-(void)yourSelector:(NSTimer*)timer
{
textField.enabled=switch.on
}

答案 2 :(得分:0)

更改开关时需要监听:

[switch addTarget:self action:@selector(switched:) forControlEvents:UIControlEventValueChanged];

然后:

- (void)switched:(UISwitch *)switch {
    if (switch.on == YES) {
        textField.enabled = YES;
    } else {
        textField.enabled = NO;
    }
}

或更简单:

- (void)switched:(UISwitch *)switch {
    textField.enabled = switch.on;
}