【问题标题】:UITextField.enabled to Yes or No according to UISwitch.onUITextField.enabled 根据 UISwitch.on 设置为 Yes 或 No
【发布时间】:2014-04-13 13:05:36
【问题描述】:

我想让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;
}

谢谢。

【问题讨论】:

  • 这些代码片段里面的方法是什么?

标签: ios objective-c uitextfield uiswitch


【解决方案1】:

你需要给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;
}

【讨论】:

    【解决方案2】:

    顺便说一句,你可以替换

    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
    }
    

    【讨论】:

    • 定时器到底是干什么用的?!
    【解决方案3】:

    切换开关时需要监听:

    [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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 2014-10-19
      相关资源
      最近更新 更多