Is there any way to add UIPickerView into UIAlertController (Alert or ActionSheet) in Swift?

后端 未结 11 1331
旧巷少年郎
旧巷少年郎 2020-12-01 06:16

I\'m totally new to swift (and iOS programming at all), but I started messing around with it (it wasn\'t a good idea when everything is still beta version :D). So I tried to

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 07:23

    You can use similar code in In iOS8 / Swift to add your own controls into an alert (instead of an action sheet) that pops up in the middle of the screen.

    The only problem I had with doing this with alert.addSubView was that the alert view only sizes itself according to the controls you have added through the class methods. You have to then add your own constraints to make sure that the alert encompasses all your controls.

    I've added an example here as the original question asked for Alert or ActionSheet

    func addAlert(){
    
        // create the alert
        let title = "This is the title"
        let message = "This is the message"
        var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert);
        alert.modalInPopover = true;
    
        // add an action button
        let nextAction: UIAlertAction = UIAlertAction(title: "Action", style: .Default){action->Void in
            // do something
        }
        alert.addAction(nextAction)
    
        // now create our custom view - we are using a container view which can contain other views
        let containerViewWidth = 250
        let containerViewHeight = 120
        var containerFrame = CGRectMake(10, 70, CGFloat(containerViewWidth), CGFloat(containerViewHeight));
        var containerView: UIView = UIView(frame: containerFrame);
    
        alert.view.addSubview(containerView)
    
        // now add some constraints to make sure that the alert resizes itself
        var cons:NSLayoutConstraint = NSLayoutConstraint(item: alert.view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: containerView, attribute: NSLayoutAttribute.Height, multiplier: 1.00, constant: 130)
    
        alert.view.addConstraint(cons)
    
        var cons2:NSLayoutConstraint = NSLayoutConstraint(item: alert.view, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: containerView, attribute: NSLayoutAttribute.Width, multiplier: 1.00, constant: 20)
    
        alert.view.addConstraint(cons2)
    
        // present with our view controller
        presentViewController(alert, animated: true, completion: nil)
    
    }
    

提交回复
热议问题