如何快速添加“基本输入”与 UIAlertController 的 textField 一起使用?

问题描述

我想添加功能,例如,如果 textfield 中没有任何字母并按下确认按钮,则 textfield 打印 "you must need to write folder name",并在显示打印时停止操作。我在谷歌找到了一些例子,但我不知道如何调整我的代码

func folderAdDalert() {
    let alert = UIAlertController(title: "Folder name",message: nil,preferredStyle: .alert)

    alert.addTextField {(folderAddTF) in folderAddTF.placeholder = "Please add folder name"
        print("+ clicked." )
    }
    
    let action = UIAlertAction(title: "Confirm",style: .default){ (_) in
        guard let folder = alert.textFields?.first?.text else { return }
        
        print("folderName: \(folder)")
        self.folderNames.append(folder)
        self.collectionView.reloadData()
    }
    let cancel = UIAlertAction(title: "Cancel",style: UIAlertAction.Style.default,handler: nil)
        
        alert.addAction(action)
        alert.addAction(cancel)
        present(alert,animated: true,completion: nil)
    }
}

enter image description here

解决方法

您的方式是正确的,但是在这里您需要检查文本字段是否为空,在用户按下确认按钮时进行验证

let action = UIAlertAction(title: "Confirm",style: .default){ (_) in
            guard let folder = alert.textFields?.first?.text,!folder.isEmpty else {
             self.present(alert,animated: true,completion: nil)
                if let getPlaceholder = alert.textFields?.first,let placeHolderText = getPlaceholder.placeholder{
                    getPlaceholder.attributedPlaceholder = NSAttributedString(string: placeHolderText,attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
                }
                return }
            print("folderName: \(folder)")
        }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...