如何在 Swift 中将 TextField 添加到 UIAlertView

Posted

技术标签:

【中文标题】如何在 Swift 中将 TextField 添加到 UIAlertView【英文标题】:How to add a TextField to UIAlertView in Swift 【发布时间】:2014-06-07 04:19:36 【问题描述】:

我有这段代码,但我不知道如何在 UIAlertView 中显示文本字段。

var altMessage = UIAlertController(title: "Warning", message: "This is Alert Message", preferredStyle: UIAlertControllerStyle.Alert)
altMessage.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(altMessage, animated: true, completion: nil)

我有这个 textfield 的代码,如何在 UIAlerView 中显示它

var my:UITextField = UITextField(frame: CGRectMake(0, 0, 10, 10))

我也试过这个代码:

var alert = UIAlertView()
alert.title = "Enter Input"
alert.addButtonWithTitle("Done")
alert.alertViewStyle = UIAlertViewStyle.PlainTextInput
alert.addButtonWithTitle("Cancel")
alert.show()

当我指定 AlertStyle 纯文本时,它会显示一个带有默认占位符“登录”的 TextField。我想改变它,我想显示一个小数点键盘。我还想处理用户在 textField 中输入的值。有人可以帮我解决这个问题吗?

【问题讨论】:

【参考方案1】:

您可以通过以下方式访问文本字段:

let textField = alert.textFieldAtIndex(0)

然后更改占位符文本:

textField.placeholder = "Foo!"

以及键盘类型:

textField.keyboardType = ...

【讨论】:

好的,我明白了。但是如何将 textField 添加到 AlertView,>? 你已经得到了那个部分,将alertViewStyle 设置为TextInput 变体之一。您只能在警报中包含零两个文本字段,如果您想要更多,则必须自己滚动。 好吧,那太棒了……!!我该如何处理 TexttInput .?? alert.textFieldAtIndex(0).text 是第一个字段中的文本。 我知道,我在问如何处理这些按钮,我想在用户单击“完成”按钮时返回值。??【参考方案2】:

试用此代码(使用 swift):

func configurationTextField(textField: UITextField!)
    
        println("configurat hire the TextField")

        if let tField = textField 

            self.textField = textField!        //Save reference to the UITextField
            self.textField.text = "Hello world"
        
    


 func handleCancel(alertView: UIAlertAction!)
        
           println("User click Cancel button") 
           println(self.textField.text)
        

 var alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: UIAlertControllerStyle.Alert)

    alert.addTextFieldWithConfigurationHandler(configurationTextField)

    alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:handleCancel))
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: (UIAlertAction)in
            println("User click Ok button")
            println(self.textField.text)
        ))
    self.presentViewController(alert, animated: true, completion: 
            println("completion block")
        )

你能看到我的回答吗here

【讨论】:

如果我想在警报中添加两个文本字段怎么办?如何做到这一点? @JayprakashDubey 试试这个帖子nshipster.com/uialertcontroller,你可以在那里找到一个包含两个文本文件的登录表单。 问题是关于 UIAlertView(已弃用)而不是 UIAlertAction(>ios8)。这个答案是题外话。【参考方案3】:

目标C

 UIAlertView *alertView =  [[UIAlertView alloc]initWithTitle:@"Duplicate file" message:@"A file with the same name already exists." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
 alertView.alertViewStyle = UIAlertViewStylePlainTextInput;

 [[alertView textFieldAtIndex:0] setText:@"Filename"];
 [[alertView textFieldAtIndex:0] setPlaceholder:@"Enter Filename"];
 [alertView show];

Swift 2.3

func doSomething()
    var alert = UIAlertController(title: "Duplicate file", message: "A file with the same name already exists.", preferredStyle: UIAlertControllerStyle.Alert)

    alert.addTextFieldWithConfigurationHandler(configurationTextField)

    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: (UIAlertAction)in
         print("User click Ok button")
         print(self.textField.text)
    ))

 self.presentViewController(alert, animated: true, completion: 
     print("completion block")
 )


 func configurationTextField(textField: UITextField!)
     textField.text = "Filename"
 

Swift 3

func doSomething()
    var alert = UIAlertController(title: "Duplicate file", message: "A file with the same name already exists.", preferredStyle: UIAlertControllerStyle.alert)

    alert.addTextField(configurationHandler: configurationTextField)

    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: (UIAlertAction)in
        print("User click Ok button")
        print(self.textField.text)
    ))

    self.present(alert, animated: true, completion: 
        print("completion block")
    )


func configurationTextField(textField: UITextField!)
    textField.text = "Filename"

【讨论】:

【参考方案4】:

斯威夫特 5

public func alertWithTextField(title: String? = nil, message: String? = nil, placeholder: String? = nil, completion: @escaping ((String) -> Void) =  _ in ) 
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    alert.addTextField()  newTextField in
        newTextField.placeholder = placeholder
    
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)  _ in completion("") )
    alert.addAction(UIAlertAction(title: "Ok", style: .default)  action in
        if
            let textFields = alert.textFields,
            let tf = textFields.first,
            let result = tf.text
         completion(result)  
        else
         completion("") 
    )
    navigationController?.present(alert, animated: true)

用法:

alertWithTextField(title: "bork", message: "borkborkbork", placeholder: "bork?")  result in
    print(result)

【讨论】:

致命错误:NavigationController 无法显示 。只允许 NavigationController 的子类。:文件 /Users/tamim/Projects/chatmio-ios/Display/Display/NavigationController.swift,第 1020 行 @TamimAttafi 如果您不在UINavigationController 中使用此代码,请将navigationController 替换为self【参考方案5】:
            var inputTextField: UITextField?

            //Create the AlertController
            let actionSheetController: UIAlertController = UIAlertController(title: "Rename", message: "", preferredStyle: .Alert)

            //Create and add the Cancel action
            let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel)  action -> Void in
        //Do some stuff
            
            actionSheetController.addAction(cancelAction)
            //Create and an option action
            let nextAction: UIAlertAction = UIAlertAction(title: "OK", style: .Default)  action -> Void in
        //Do some other stuff
            
            actionSheetController.addAction(nextAction)
            //Add a text field
            actionSheetController.addTextFieldWithConfigurationHandler  textField -> Void in
        // you can use this text field
        inputTextField = textField
            

            //Present the AlertController
            self.presentViewController(actionSheetController, animated: true, completion: nil)

【讨论】:

【参考方案6】:

Swift 3

    let alert = UIAlertController(title: "Alert Ttitle", message: "Alert Message", preferredStyle:
        UIAlertControllerStyle.alert)

    alert.addTextField(configurationHandler: textFieldHandler)

    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: (UIAlertAction)in


    ))

    self.present(alert, animated: true, completion:nil)

func textFieldHandler(textField: UITextField!)
    
        if (textField) != nil 
            textField.text = "Filename"
        
    

【讨论】:

【参考方案7】:

斯威夫特 4

var textField: UITextField?

func configurationTextField(textField: UITextField!) 
    if (textField) != nil 
        self.textField = textField!        //Save reference to the UITextField
        self.textField?.placeholder = "Some text";
    


func openAlertView() 
    let alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: UIAlertControllerStyle.alert)
    alert.addTextField(configurationHandler: configurationTextField)
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:nil))
    alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: (UIAlertAction) in
        print("User click Ok button")
    ))
    self.present(alert, animated: true, completion: nil)

【讨论】:

【参考方案8】:

为 swift 3 更新:

用于以下简单代码:

    func showAlertWithTwoTextFields() 

        let alertController = UIAlertController(title: "Add Event", message: "Enter event and it's description", preferredStyle: .alert)

        let saveAction = UIAlertAction(title: "Save", style: .default, handler: 
            alert -> Void in

            let eventNameTextField = alertController.textFields![0] as UITextField
            let descriptionTextField = alertController.textFields![1] as UITextField

            print("firstName \(String(describing: eventNameTextField.text)), secondName \(String(describing: descriptionTextField.text))")

            if eventNameTextField.text != "" || descriptionTextField.text != ""

            else
               // self.showAlertMessageToUser(title: "Alert", messageToUser: "Fields should not be empty, Please enter given info...")
// Show Alert Message to User As per you want
            

        )

        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: 
            (action : UIAlertAction!) -> Void in

        )

        alertController.addTextField  (textField : UITextField!) -> Void in
            textField.placeholder = "Enter event Name"
        
        alertController.addTextField  (textField : UITextField!) -> Void in
            textField.placeholder = "Enter event description in short"
        

        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)

        self.present(alertController, animated: true, completion: nil)
    

// 享受编码...!

【讨论】:

【参考方案9】:

斯威夫特 2.2

import UIKit

extension UIAlertController 
    // MARK: - UIAlertController+Present

    private struct ButtonsName 
        static let Ok = NSLocalizedString("uIAlertController.buttonName.ok", comment: "")
        static let Cancel = NSLocalizedString("uIAlertController.buttonName.cancel", comment: "")
    


    class func suggestionAlertViewWithTitle(title:String?, placeholder:String, message:String, presenter:UIViewController, destructive:Bool = false,
                                            okButtonCompletion:((enteredSuggestion:String?)->Void)?, cancelButtonCompletion:(()->Void)?, presentCompletion:(()->Void)?) 
        var alertTitle = UIAlertController.appName()
        if let userTitle = title 
            alertTitle = userTitle
        

        let controller = UIAlertController(title: alertTitle, message: message, preferredStyle: .Alert)
        let okAction = UIAlertAction(title: ButtonsName.Ok, style: destructive == true ? .Destructive : .Default)  (action) in
            if let okButtonCompletion = okButtonCompletion 
                let text = controller.textFields?.first?.text
                dispatch_async(dispatch_get_main_queue(), 
                    okButtonCompletion(enteredSuggestion: text)
                )
            
        
        let cancelAction = UIAlertAction(title: ButtonsName.Cancel, style: .Cancel)  (action) in
            if let cancelButtonCompletion = cancelButtonCompletion 
                dispatch_async(dispatch_get_main_queue(), 
                    cancelButtonCompletion()
                )
            
        

        controller.addAction(okAction)
        controller.addAction(cancelAction)
        controller.addTextFieldWithConfigurationHandler  (textField) in
            textField.placeholder = placeholder
        

        dispatch_async(dispatch_get_main_queue(), 
            presenter.presentViewController(controller, animated: true, completion: presentCompletion)
        )
    

    // MARK: - Private

    private static func appName () -> String 
        return NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String
    

用法:

    UIAlertController.suggestionAlertViewWithTitle(nil, placeholder: placeholder, message: message,
                                                          presenter: self, destructive: false,
                                                          okButtonCompletion:  (enteredSuggestion) in
                self.logger.sendAllLogs(self.currentUser, suggestedTitle: enteredSuggestion)
        , cancelButtonCompletion:nil, presentCompletion: nil)

有点重载,但你总是可以让一些参数可选或/和默认

【讨论】:

【参考方案10】:

我看到您已经在使用新的 UIAlertController —— 好主意,因为如果您使用 Swift,旧 API 几乎没有用处。但是alert.textFieldAtIndex: 不适用;仅供UIAlertView使用。

幸运的是,UIAlertController has a method for adding text fields。

【讨论】:

以上是关于如何在 Swift 中将 TextField 添加到 UIAlertView的主要内容,如果未能解决你的问题,请参考以下文章

在 SwiftUI 中向 TextField/SecureField 添加图像,向占位符文本添加填充

如何在 swift 中添加与 UIAlertController 的 textField 一起使用的“基本类型”?

如何在 Swift 2.0 中使用标签将 TextField 添加到 Cell

swift如何使用TextField添加子视图TagView编程?

获取 Button 和 Textfield 数据,当它们在 swift 5 中以编程方式添加时

如何在swift中将逗号添加到数字?