UIAlertController中的中心UITextField

UIAlertController中的中心UITextField

当我使用情节提要元素(文本视图,标签)时,一切正常,并且警报控制器中间有文本字段。但是,当我想通过代码(情节提要以外的文本字段)创建代码时,它不起作用。这是代码。

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)

        var newProjectTextField = UITextField(frame: CGRectMake(0, 0, 200, 31))
        newProjectTextField.center = CGPointMake(160, 284)
        newProjectTextField.textAlignment = NSTextAlignment.Center
        newProjectTextField.placeholder = "New project's name"

        alert.view.addSubview(newProjectTextField)

        // 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)

        var centerXConstraint:NSLayoutConstraint = NSLayoutConstraint(item: newProjectTextField, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: alert.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.00, constant: 0.0)
        alert.view.addConstraint(centerXConstraint)

        var centerYConstraint:NSLayoutConstraint = NSLayoutConstraint(item: newProjectTextField, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: alert.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.00, constant: 0.0)
        alert.view.addConstraint(centerYConstraint)

        // present with our view controller
        presentViewController(alert, animated: true, completion: nil)
    }

最佳答案

newProjectTextField.center = CGPointMake(250,120)


这将居中,而不会扩展y轴。不知道这是否正是您要寻找的。

关于ios - UIAlertController中的中心UITextField,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29279352/

10-13 05:05