以编程方式切换UIAlert控制器

时间:2016-01-27 05:57:30

标签: ios swift uiswitch uialertcontroller

我正在swift中创建一个注册对话框,其中有3个文本字段和一个Switch,我成功添加了三个文本字段两个Alert。以下代码显示相同。

 let alertController = UIAlertController(title: "Register", message: "", preferredStyle: .Alert)
    let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
        // ...

        exit(0)
    }
    alertController.addAction(cancelAction)

    let OKAction = UIAlertAction(title: "Sign UP", style: .Default) { (action) in
        // ...
        let name0 = alertController.textFields![0] as UITextField
        print("Text field: \(name0.text)")

        let email1 = alertController.textFields![1] as UITextField
        print("Text field: \(email1.text)")

        let company2 = alertController.textFields![2] as UITextField
        print("Text field: \(company2.text)")


    }

    alertController.addAction(OKAction)

    alertController.addTextFieldWithConfigurationHandler { (textField) in
        textField.placeholder = "Name"
        textField.keyboardType = .EmailAddress
    }

    alertController.addTextFieldWithConfigurationHandler { (textField) in
        textField.placeholder = "Email"
        textField.secureTextEntry = false
    }

    alertController.addTextFieldWithConfigurationHandler { (textField) in
        textField.placeholder = "Company"
        textField.secureTextEntry = false
    }


            self.presentViewController(alertController, animated: true) {
                // ...
            }

现在我需要以编程方式将一个开关添加到Alert View。我们在Swift2中这样做。有可能吗?,我是Swift的新手。

4 个答案:

答案 0 :(得分:9)

这可能会对你有所帮助。

alertController.view.addSubview(createSwitch())之后的上述代码中添加此方法调用alertController.addAction(OKAction)

func createSwitch () -> UISwitch{


    let switchControl = UISwitch(frame:CGRectMake(10, 20, 0, 0));
    switchControl.on = true
    switchControl.setOn(true, animated: false);
    switchControl.addTarget(self, action: "switchValueDidChange:", forControlEvents: .ValueChanged);
    return switchControl
}

func switchValueDidChange(sender:UISwitch!){

    print("Switch Value : \(sender.on))")
}

OutPut:

enter image description here

答案 1 :(得分:4)

您可以使用TextField的RightView添加按钮。添加一个开关会很不错,但是开关不适合TextField高度,也不能改变高度。为此,您可以添加一个按钮并使用图像来制作TickBox。

AlertController with TickBox

我已将其从项目中删除,因此示例图像比下面的图像多一点。

在ViewController标题中添加TextField Delegate

@interface CustomTableViewController : UITableViewController <UITextFieldDelegate>

然后创建AlertController并添加TextField

// create an alert controller
UIAlertController *alertWithText = [UIAlertController alertControllerWithTitle:title message:body preferredStyle:UIAlertControllerStyleAlert];

// create the actions handled by each button
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

}];

UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

}];

// add the actions to the alert
[alertWithText addAction:action1];
[alertWithText addAction:action2];

// Establish the weak self reference
__weak typeof(self) weakSelf = self;

[alertWithText addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {

    // Create button
    UIButton *checkbox = [UIButton buttonWithType:UIButtonTypeCustom];
    [checkbox setFrame:CGRectMake(2 , 2, 18, 18)];  // Not sure about size
    [checkbox setTag:1];
    [checkbox addTarget:weakSelf action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

    // Setup image for button
    [checkbox.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [checkbox setImage:[UIImage imageNamed:@"unchecked_checkbox.png"] forState:UIControlStateNormal];
    [checkbox setImage:[UIImage imageNamed:@"checked_checkbox.png"] forState:UIControlStateSelected];
    [checkbox setImage:[UIImage imageNamed:@"checked_checkbox.png"] forState:UIControlStateHighlighted];
    [checkbox setAdjustsImageWhenHighlighted:TRUE];

    // Setup the right view in the text field
    [textField setClearButtonMode:UITextFieldViewModeAlways];
    [textField setRightViewMode:UITextFieldViewModeAlways];
    [textField setRightView:checkbox];

    // Setup Tag so the textfield can be identified
    [textField setTag:-1];
    [textField setDelegate:weakSelf];

    // Setup textfield
    [textField setText:@"Essential"];  // Could be place holder text

}];

[self presentViewController:alertWithText animated:YES completion:nil];

如果您纯粹希望该行为勾号,则需要停止编辑文本字段。

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if(textField.tag == -1){
        return NO;
    }

    return YES;
} 

您对按钮的操作

-(void)buttonPressed:(UIButton*)sender {

    if(sender.selected){
        [sender setSelected:FALSE];
    } else {
        [sender setSelected:TRUE];
    }
}

这里也有一些勾选框图片(那里有很多,你甚至可以进行切换并尝试动画)。

Unchecked Box Checked Box

答案 2 :(得分:1)

这个答案是针对目标C的。它不使用文本字段,但确实将UISwitch添加到UIAlertController上,这是主要问题的要求。我没有在SO上找到任何能做到这一点的东西,所以我在这里发布此答案,而不是发布另一个将重复出现的问题。

此解决方案用于使用户能够对UITableView菜单(项目列表中的菜单...)进行排序

由于@technerd的回答,我还使UISwitch更改了UILabel的文本,该文本也位于同一UIAlertController视图上。当UILabel值更改时,它将在层中使用KVC(键值编码)将UISwitch id传递给目标操作。 (请参见代码中的setOrderLabelText方法)

我还试图避开在标题或消息中添加换行符(“ \ n \ n \ n \ n”)的技巧,以通过使用约束人为地移动内容。

我使用水平UIStackView来保持UISwitch及其对应的UILabel,然后使用约束来设置UIStack的顶部锚点,并使用高度约束UIAlertController视图,使其足够大以包含UIStackView和UIAlertController标题。

我认为无法获得UIAlertController标题的高度或操作按钮的高度。因此,我想出了在iPhone X和iPad 2上都能很好地工作的价值观。正如在其他SO答案中一样,我可能会想出一种本土解决方案(或在GitHub上找到一种解决方案),以使其更加强大。但是,由于我已经走了这么远,并且从其他很棒的SO答案中得到了很多,所以我想回馈一点并分享我的结果。

以下是屏幕截图:

enter image description here

这是代码:

// using KVC, set the label text based on the label tag and toggle the tag
- (void)setOrderLabelText:(UISwitch *)orderSwitch {
    UILabel *label = (UILabel *)[orderSwitch.layer valueForKey:@"label"];

    label.text = label.tag ? @"Ascending" : @"Descending";

    label.tag = label.tag ? 0 : 1;

}

// sort the data based on the user's selections
- (IBAction)sort:(UIButton *)sortButton {    
    UILabel *label = [[UILabel alloc] init];
    label.text = @"Ascending";
    label.textColor = UIColor.grayColor;
    label.tag = 0;
    [label sizeToFit];

    UISwitch *orderSwitch = [[UISwitch alloc] init];
    orderSwitch.on = YES;
    [orderSwitch setOn:YES animated:YES];

    // allow the switch to change the text in the label using KVC (key-value coding)
    [orderSwitch addTarget:self action:@selector(setOrderLabelText:) forControlEvents:UIControlEventValueChanged];
    [orderSwitch.layer setValue:label forKey:@"label"];

    UIStackView *stackView = [[UIStackView alloc] init];
    stackView.axis = UILayoutConstraintAxisHorizontal;
    stackView.spacing = 8;

    [stackView addArrangedSubview:orderSwitch];
    [stackView addArrangedSubview:label];

    UIAlertController *alert = [UIAlertController
                                alertControllerWithTitle: @"Sort Projects By"
                                message: nil
                                preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *createdButton = [UIAlertAction
                                  actionWithTitle:@"Created"
                                  style:UIAlertActionStyleDestructive
                                  handler:^(UIAlertAction * action) {
                                      [self sortBy:@"created" ascending:orderSwitch.isOn];
                                  }];
    UIAlertAction *titleButton = [UIAlertAction
                                  actionWithTitle:@"Title"
                                  style:UIAlertActionStyleDestructive
                                  handler:^(UIAlertAction * action) {
                                      [self sortBy:@"title" ascending:orderSwitch.isOn];
                                  }];
    UIAlertAction *subtitleButton = [UIAlertAction
                                  actionWithTitle:@"Subtitle"
                                  style:UIAlertActionStyleDestructive
                                  handler:^(UIAlertAction * action) {
                                      [self sortBy:@"subtitle" ascending:orderSwitch.isOn];
                                  }];
    UIAlertAction *cancelButton = [UIAlertAction
                                   actionWithTitle:@"Cancel"
                                   style:UIAlertActionStyleCancel
                                   handler:^(UIAlertAction * action) {
                                   }];

    // add action buttons to the alert
    [alert addAction:createdButton];
    [alert addAction:titleButton];
    [alert addAction:subtitleButton];
    [alert addAction:cancelButton];

    [alert.view addSubview:stackView];

    // center the stack in the alert
    [stackView.centerXAnchor constraintEqualToAnchor:alert.view.centerXAnchor].active = YES;

    // turn off the autoresizing mask or things get weird
    stackView.translatesAutoresizingMaskIntoConstraints = NO;

    // use a topAnchor constraint to place the stackview, just below the title
    // TODO:  figure out how to get the height of the alert title (use 64 for now)
    [stackView.topAnchor constraintEqualToAnchor:alert.view.topAnchor constant:64].active = YES;

    // layout now to set the view bounds so far - NOTE this does not include the action buttons
    [alert.view layoutIfNeeded];

    // use a height constraint to make the alert view big enough to hold my stack view
    // NOTE:  strange, but this must include the header view AND all the action buttons
    // TODO:  figure out how to get the height of the action buttons (use 52 for each action button for now)
    CGFloat height = alert.view.bounds.size.height + alert.actions.count * 52 + stackView.bounds.size.height;
    [alert.view.heightAnchor constraintEqualToConstant:height].active = YES;

    [self presentViewController:alert animated:YES completion:nil];
}

答案 3 :(得分:0)

如果您在iOS 13上使用以上Recycled Steelanswer,则可以使用SF符号代替PNG。它将解决您可能遇到的任何缩放问题。

    checkbox.imageView.tintColor = UIColor.blackColor;
    if (@available(iOS 13.0, *)) {
        [checkbox setImage: [UIImage systemImageNamed:@"square"] forState: UIControlStateNormal];
        [checkbox setImage: [UIImage systemImageNamed:@"checkmark.square"] forState: UIControlStateHighlighted];
        [checkbox setImage: [UIImage systemImageNamed:@"checkmark.square"] forState: UIControlStateSelected];
    }