UIAlertController - change size of text fields and add space between them

情到浓时终转凉″ 提交于 2019-12-18 08:33:28

问题


My alert looks like this:

Is it possible to make inputs bigger and add space between them? Here is a snippet from my code. I tried changing the frame property of the second text field but it didn't help:

let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)

// Add the textfields
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
  textField.placeholder = "Vaše jméno"

})

alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
  textField.placeholder = "Společné heslo"

  var oldFrame = textField.frame
  oldFrame.origin.y = 40
  oldFrame.size.height = 60
  textField.frame = oldFrame
})

回答1:


UIAlertController views are intended to be simple and not customizable. If you make your own presented view controller, then the view belongs to you and you can do anything you like.




回答2:


WARNING: only use this solution as a last resort! If you want to fine-tune the look of your alert controller, use a custom alert view. Take a look at this question for details.

As a hacky solution, you can use a third text field between the two as a separator and disable it. Also, you can give it a custom height using this mehtod.

To avoid getting this extra text field in focus, use the UITextFieldDelegate method textFieldShouldReturn(_:) to get the second text field to focus instead.

class AlertViewController: UITextFieldDelegate {
    [...]

    var firstTextField: UITextField!
    var secondTextField: UITextField!

    func setUpAlert() {
        [...]

        alert.addTextField { [weak self] textField in
            self?.firstTextField = textField
            textField.delegate = self
        }

        alert.addTextField { textField in
            textField.addConstraint(textField.heightAnchor.constraint(equalToConstant: 2))
            textField.isEnabled = false
        }

        alert.addTextField { [weak self] textField in
            self?.secondTextField = textField
        }

        [...]
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == firstTextField {
            secondTextField?.becomeFirstResponder()
        }

        return true
    }
}

Result:

Unfortunately, you cannot hide the extra text field, but at least you can give it a background:

textField.backgroundColor = .black

Result:



来源:https://stackoverflow.com/questions/33787115/uialertcontroller-change-size-of-text-fields-and-add-space-between-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!