UITEXTFIELD将数据输入到警报框,然后单击确定

时间:2018-07-05 11:25:56

标签: ios swift uitextfield

我正在实施用户表单,并在用户按下SUBMIT按钮时填写所有字段,并在用户同意时创建了警报框(警报框属于“条款和条件”),并从用户那里获取详细信息。它必须获取所有UITextField个输入数据。

我创建了一个类,在该类中,我存储了textField中的值,并且当用户单击“同意”时,我不知道如何调用该类。

func getvalueoftextfield() {
    let UserDestination: String = Choose_Destination.text!
    print(UserDestination)

    let UserDenomination: String = Choose_Denomination.text!
    print(UserDenomination)

    let UserEnteredDenomination: String = manual_denominaton_textfield.text!
    print(UserEnteredDenomination)

    let UserEmail: String = Email_textfield.text!
    print(UserEmail)

    let UserEnteredEmailConfirm: String = confirm_email_validation.text!
    print(UserEnteredEmailConfirm)

    let UserEnteredReceiversName: String = receivers_name_textfirld.text!
    print(UserEnteredReceiversName)

    let UserEnteredSendersName: String = senders_name_textfield.text!
    print(UserEnteredSendersName)

    let UserMessage: String = message_textView.text!
    print(UserMessage)

   // let datacombined: String = " User Name: \(Choose_Destination.text!) \nPassword: \(Choose_Denomination.text!)\n "
}

警报框的代码

alert.addAction(UIAlertAction(title: "Agree", style: UIAlertActionStyle.default, handler: getvalueoftextfield))

这不起作用。请帮助我

整个控制器文件

//
//  e-GiftsViewController.swift
//  GIFT_VOUCHER
//
//  Created by cbazaar R&D IT Infra on 23/06/18.
//  Copyright © 2018 cbazaar R&D IT Infra. All rights reserved.
//

import UIKit

class e_GiftsViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate, UITextViewDelegate{

    @IBOutlet weak var paynow_button: UIButton!
    @IBOutlet weak var Error_label: UILabel!
    // outlet for destination of user
    @IBOutlet weak var Choose_Destination: UITextField!

    @IBOutlet weak var scroll: UIScrollView!
    // outlet for denomination
    @IBOutlet weak var Choose_Denomination: UITextField!

    @IBOutlet weak var message_textView: UITextView!


    @IBOutlet weak var receivers_name_textfirld: UITextField!

    @IBOutlet weak var senders_name_textfield: UITextField!

    @IBOutlet weak var manual_denominaton_textfield: UITextField!

    @IBOutlet weak var Email_textfield: UITextField!

    @IBOutlet weak var confirm_email_validation: UITextField!

    //Contents for picker view
    var Destination_receiver = [["India"],["Europe","Australia","New Zealand","USA & Rest of the World"]]

    var denomination = [[" Rs.500","Rs.1000","Rs.1500","Rs.2000","Rs.2500","Rs.3000","Rs.3500","Rs.4000","Rs.4500","Rs.5000"],
                                ["100","150","200","250","300","350","400","450","500"]]

  //  var denomination_rest = ["100","150","200","250","300","350","400","450","500"]

    //picker view
    let destination_pickerview = UIPickerView()
    let denomination_picerview = UIPickerView()


  //  var x = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        Error_label.isHidden = true

        //delegate for Manual denomination selection
        manual_denominaton_textfield.delegate = self

       // message_textView.delegate = self

//        destination_pickerview.tag = 0
//        denomination_picerview.tag = 1

        destination_pickerview.delegate = self
        destination_pickerview.dataSource = self

        denomination_picerview.delegate = self
        denomination_picerview.dataSource = self


        create_toolbar()




        // Destination of receivers modification
        Choose_Destination.inputView = destination_pickerview
        Choose_Destination.placeholder = "Select Destination"

        // Denomination Amount from receiver's inputview and modifications
        Choose_Denomination.inputView = denomination_picerview
        Choose_Denomination.placeholder = "Select Gift Amount"

        // Enter Denomination Textfield placeholder
        manual_denominaton_textfield.placeholder = "Enter Denomination Amount"

        //Enter receivers name place holder
        receivers_name_textfirld.placeholder = "Enter Receivers Name"

        //Enter Senders Name
        senders_name_textfield.placeholder = "Enter Senders Name"

        // Email placeholder
        Email_textfield.placeholder = "Enter Receiver's Email"

        //Confirm Email placeholder
        confirm_email_validation.placeholder = "Confirm Receiver's Email"


        //Pay Now button changing

        paynow_button.backgroundColor = UIColor.black
        //paynow_button.layer.cornerRadius = paynow_button.frame.height / 2
        paynow_button.setTitleColor(UIColor.white, for: .normal)
        paynow_button.layer.shadowColor = UIColor(red: 249/255, green: 8/255, blue: 129/255, alpha: 1).cgColor
        //paynow_button.layer.shadowRadius = 10
       // paynow_button.layer.shadowOpacity = 0.5
        //paynow_button.layer.shadowOffset = CGSize(width: 0, height: 0)

        paynow_button.setTitleColor(UIColor.white, for: .normal)
        paynow_button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15)


        // uitxtfield design
        Choose_Destination.layer.cornerRadius = 7
        Choose_Destination.layer.shadowColor = UIColor(red: 249/255, green: 8/255, blue: 129/255, alpha: 1).cgColor
        Choose_Destination.layer.shadowRadius = 5
        Choose_Destination.layer.shadowOpacity = 0.2
        Choose_Destination.layer.shadowOffset = CGSize(width: 0, height: 0)


        Choose_Denomination.layer.shadowColor = UIColor(red: 249/255, green: 8/255, blue: 129/255, alpha: 1).cgColor
        Choose_Denomination.layer.shadowRadius = 5
        Choose_Denomination.layer.shadowOpacity = 0.2


        manual_denominaton_textfield.layer.shadowColor = UIColor(red: 249/255, green: 8/255, blue: 129/255, alpha: 1).cgColor
        manual_denominaton_textfield.layer.shadowRadius = 5
        manual_denominaton_textfield.layer.shadowOpacity = 0.2


        Email_textfield.layer.shadowColor = UIColor(red: 249/255, green: 8/255, blue: 129/255, alpha: 1).cgColor
        Email_textfield.layer.shadowRadius = 5
        Email_textfield.layer.shadowOpacity = 0.2


        confirm_email_validation.layer.shadowColor = UIColor(red: 249/255, green: 8/255, blue: 129/255, alpha: 1).cgColor
        confirm_email_validation.layer.shadowRadius = 5
        confirm_email_validation.layer.shadowOpacity = 0.2


        receivers_name_textfirld.layer.shadowColor = UIColor(red: 249/255, green: 8/255, blue: 129/255, alpha: 1).cgColor
        receivers_name_textfirld.layer.shadowRadius = 5
        receivers_name_textfirld.layer.shadowOpacity = 0.2

        senders_name_textfield.layer.shadowColor = UIColor(red: 249/255, green: 8/255, blue: 129/255, alpha: 1).cgColor
        senders_name_textfield.layer.shadowRadius = 5
        senders_name_textfield.layer.shadowOpacity = 0.2


        message_textView.layer.borderColor = UIColor(red: 249/255, green: 8/255, blue: 129/255, alpha: 1).cgColor
        message_textView.layer.borderWidth = 1

//        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
//        let newViewController =   storyBoard.instantiateViewController(withIdentifier: "egiftvoucher") as! e_GiftsViewController
//        let navController = UINavigationController.init(rootViewController: newViewController)
//        self.present(navController, animated: true, completion: nil)


        self.navigationItem.hidesBackButton = true

        let backButton = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(goToViewController(_:)))

        self.navigationItem.leftBarButtonItem = backButton




    }

    @objc func goToViewController(_ sender: UIBarButtonItem) {

        //write code here to open a view controller

        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let newViewController =   storyBoard.instantiateViewController(withIdentifier: "gotohome") as! HomeTabController
        let navController = UINavigationController.init(rootViewController: newViewController)
        self.present(navController, animated: true, completion: nil)


    }


//    @objc func goToViewController(_ sender: UIBarButtonItem) {
//        for controller in self.navigationController!.viewControllers as Array {
//            if controller.isKind(of: ChatVC.self) {
//                self.navigationController!.popToViewController(controller, animated: true)
//                break
//            } else {
//                self.navigationController?.popViewController(animated: true)
//            }
//        }
//    }




    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //Number of components in picker View
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }


    //Number of rows to be in a particular Component
    // Picker View Delegates

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        switch (pickerView){

        case destination_pickerview:

            if(globalConstants.prefs.value(forKey: "estoreId") as? NSNumber == 10) {

               // estoreId = 10
                return Destination_receiver[0].count

            }else if(globalConstants.prefs.value(forKey: "estoreId") as? NSNumber != 10){

                return Destination_receiver[1].count

            }

        case denomination_picerview:

            if(globalConstants.prefs.value(forKey: "estoreId") as? NSNumber == 10) {

                return denomination[0].count


            }else if(globalConstants.prefs.value(forKey: "estoreId") as? NSNumber != 10){

                return denomination[1].count

            }

        default:
            break
        }
        return 1
    }

    //Data to be displayed in each and every picker view

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        switch (pickerView){

        case destination_pickerview:

            if(globalConstants.prefs.value(forKey: "estoreId") as? NSNumber == 10){

                return Destination_receiver[0][row]

            }else if(globalConstants.prefs.value(forKey: "estoreId") as? NSNumber != 10){

                return Destination_receiver[1][row]

            }


        case denomination_picerview:

            if(globalConstants.prefs.value(forKey: "estoreId") as? NSNumber == 10){

                return denomination[0][row]

            } else if(globalConstants.prefs.value(forKey: "estoreId") as? NSNumber != 10){

                return denomination[1][row]
            }


        default: break
        }

        return "an error occurred"
    }


   // By selecting the data in picker view
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if (pickerView == destination_pickerview) {
           // x = row
            denomination_picerview.reloadAllComponents()

            if(globalConstants.prefs.value(forKey: "estoreId") as? NSNumber == 10){

                Choose_Destination.text = Destination_receiver[0][row]

            } else if(globalConstants.prefs.value(forKey: "estoreId") as? NSNumber != 10){

               // Choose_Denomination.text = denomination[1][row]

                Choose_Destination.text = Destination_receiver[1][row]

            }



        }else {

            Choose_Denomination.text = denomination[1][row]

        }

    }

    func getvalueoftextfield() {

        let UserDestination: String = Choose_Destination.text!
        print(UserDestination)

        let UserDenomination: String = Choose_Denomination.text!
        print(UserDenomination)

        let UserEnteredDenomination: String = manual_denominaton_textfield.text!
        print(UserEnteredDenomination)

        let UserEmail: String = Email_textfield.text!
        print(UserEmail)

        let UserEnteredEmailConfirm: String = confirm_email_validation.text!
        print(UserEnteredEmailConfirm)

        let UserEnteredReceiversName: String = receivers_name_textfirld.text!
        print(UserEnteredReceiversName)

        let UserEnteredSendersName: String = senders_name_textfield.text!
        print(UserEnteredSendersName)

        let UserMessage: String = message_textView.text!
        print(UserMessage)

       // let datacombined: String = " User Name: \(Choose_Destination.text!) \nPassword: \(Choose_Denomination.text!)\n "





    }





    // returing keyboard when clicked return
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }


    // keyboard shifting to top when textfield clicked
    func textFieldDidBeginEditing(_ textField: UITextField) {
        scroll.setContentOffset(CGPoint(x: 0,y: 550), animated: true)

    }

    func textViewDidEndEditing(_ textView: UITextView) {
         scroll.setContentOffset(CGPoint(x: 0,y: 0), animated: true)
    }


    func textfield() {

//        if  manual_denominaton_textfield.text != "" || Choose_Denomination.text == "" {
//
//           // Choose_Denomination.isEnabled = false
//            Choose_Denomination.isUserInteractionEnabled = false
//
//
//        } else if manual_denominaton_textfield.text != "" || Choose_Denomination.text != "" {
//
//           Error_label.text = "Enter Denomination and Choose Denomination Cannot have value"
//
//        } else {
//
//            manual_denominaton_textfield.isEnabled = false
//            manual_denominaton_textfield.isUserInteractionEnabled = false
//        }

    }


    //create a toolbar

    func create_toolbar(){

        let toolbar = UIToolbar()
        toolbar.barStyle = .default
        toolbar.sizeToFit()
        //done button creation

        let donebuttontoolbar = UIBarButtonItem(title: "Done", style: .plain
            , target: self, action: #selector(doneclick))

        let spacebutton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)

        let cancelbutton = UIBarButtonItem(title: "Cancel", style: .plain
            , target: self, action: #selector(cancelclick))

        toolbar.setItems([donebuttontoolbar ,spacebutton, cancelbutton], animated: false)

        Choose_Denomination.inputAccessoryView = toolbar
        Choose_Destination.inputAccessoryView = toolbar
    }

    @objc func doneclick()
    {
        Choose_Destination.resignFirstResponder()
        Choose_Denomination.resignFirstResponder()

    }

    @objc func cancelclick()
    {
        Choose_Destination.text = ""
        Choose_Destination.resignFirstResponder()
        Choose_Denomination.text = ""
        Choose_Denomination.resignFirstResponder()
    }

    // MESSAGE TEXTFIELD limit characters
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let currentText = message_textView.text as NSString
        let updatedText = currentText.replacingCharacters(in: range, with: text)
        return updatedText.utf8CString.count <= 300
    }

    func isValidEmail(emailID:String) -> Bool {
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: emailID)
    }




    @IBAction func Submit_Button(_ sender: Any) {

        Error_label.isHidden = true
        textfield()
        view.endEditing(true)

        guard let email = Email_textfield.text, Email_textfield.text?.utf8CString.count != 0 || Email_textfield.text == "" else {
            Error_label.isHidden = false
            Error_label.text = "Please enter your email"
            return
        }

        if receivers_name_textfirld.text == "" || senders_name_textfield.text == "" {
            Error_label.isHidden = false
            Error_label.text = "Receiver and Sender name cannot be empty"
        }   else if message_textView.text == "" {
            Error_label.isHidden = false
            Error_label.text = "Message Value Cannot be Empty"
        }
        else{
            let alert = UIAlertController (title: "Terms and Condition", message: "\nThe gift voucher being gifted can only be redeemed only at Cbazaar\n  \nThis is non - transferrable.\n  \n This Gift voucher will be added as a store credit to the recipient.\n \nYou may use the store credit in multiple transaction to realize its full value.\n \nNo cash refund, in part or full will be made against this gift voucher.\n \nIf purchase value exceeds the value of gift voucher, differential value can be paid by other means.\n \nUsage shall be administered by the program rules established by Net Avenue Technologies Pvt Ltd.", preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "Disagree", style: UIAlertActionStyle.default, handler: nil))
            alert.addAction(UIAlertAction(title: "Agree", style: UIAlertActionStyle.default, handler: nil))





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

        }


        if isValidEmail(emailID: email) == false {
            Error_label.isHidden = false
            Error_label.text = "Please Enter Valid Email Address"
        }
        else if confirm_email_validation.text == "" {
            Error_label.isHidden = false
            Error_label.text = " Confirm Email Cannot be Empty"
        }
        else if confirm_email_validation.text != Email_textfield.text{
            Error_label.isHidden = false
            Error_label.text = "Confirm Email Cannot be different"
        }
        else if confirm_email_validation.text == Email_textfield.text {
            print("email entered correctly")
        }

        if Choose_Denomination.text == "" && manual_denominaton_textfield.text != ""{

            Choose_Denomination.isUserInteractionEnabled = false

        } else if manual_denominaton_textfield.text == "" && Choose_Denomination.text != ""{

            manual_denominaton_textfield.isUserInteractionEnabled = false

        } else if manual_denominaton_textfield.text != "" && Choose_Denomination.text != ""{

            Error_label.text = "Choose Denomination and Enter Denomination both Cannot have value"
        }

        if Choose_Destination.text == "" {
            Error_label.isHidden = false
            Error_label.text = "Choose Destination of Receiver"
        } else if Choose_Denomination.text == "" && manual_denominaton_textfield.text == "" {
            Error_label.isHidden = false
            Error_label.text = "Choose Denomination or Enter Denomination"
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我认为您的代码很好,只需要做一些更改。您需要从此方法返回组合字符串。

更新以下方法。

func getvalueoftextfield() -> String {
    let UserDestination: String = Choose_Destination.text!
    print(UserDestination)

    let UserDenomination: String = Choose_Denomination.text!
    print(UserDenomination)

    let UserEnteredDenomination: String = manual_denominaton_textfield.text!
    print(UserEnteredDenomination)

    let UserEmail: String = Email_textfield.text!
    print(UserEmail)

    let UserEnteredEmailConfirm: String = confirm_email_validation.text!
    print(UserEnteredEmailConfirm)

    let UserEnteredReceiversName: String = receivers_name_textfirld.text!
    print(UserEnteredReceiversName)

    let UserEnteredSendersName: String = senders_name_textfield.text!
    print(UserEnteredSendersName)

    let UserMessage: String = message_textView.text!
    print(UserMessage)

    let datacombined = String(format: "%@\n%@\n%@\n%@\n%@\n%@\n%@\n%@", UserDestination, UserDenomination, UserEnteredDenomination, UserEmail, UserEnteredEmailConfirm, UserEnteredReceiversName, UserEnteredSendersName, UserMessage
    )

    return datacombined
}

像这样显示UIAlertController

alert.addAction(UIAlertAction(title: "Agree", style: UIAlertActionStyle.default, handler: self.getvalueoftextfield()))

OR

let alertController = UIAlertController(title: AppName, message: self.getvalueoftextfield(), preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in

}

alertController.addAction(OKAction)
self.navigationController?.present(alertController, animated: true, completion: nil)

答案 1 :(得分:0)

订单应为

  1. 单击提交后,存储文本字段的所有值。

  2. 创建一个警告框,并要求用户同意所有条款和条件。

  3. 如果他接受,则使用数据,否则不使用。

或用此代码替换您的Submit_Button

@IBAction func Submit_Button(_ sender: Any) {

Error_label.isHidden = true
textfield()
view.endEditing(true)

guard let email = Email_textfield.text, Email_textfield.text?.utf8CString.count != 0 || Email_textfield.text == "" else {
    Error_label.isHidden = false
    Error_label.text = "Please enter your email"
    return
}

if receivers_name_textfirld.text == "" || senders_name_textfield.text == "" {
    Error_label.isHidden = false
    Error_label.text = "Receiver and Sender name cannot be empty"
}   else if message_textView.text == "" {
    Error_label.isHidden = false
    Error_label.text = "Message Value Cannot be Empty"
}
else{
    let alert = UIAlertController (title: "Terms and Condition", message: "\nThe gift voucher being gifted can only be redeemed only at Cbazaar\n  \nThis is non - transferrable.\n  \n This Gift voucher will be added as a store credit to the recipient.\n \nYou may use the store credit in multiple transaction to realize its full value.\n \nNo cash refund, in part or full will be made against this gift voucher.\n \nIf purchase value exceeds the value of gift voucher, differential value can be paid by other means.\n \nUsage shall be administered by the program rules established by Net Avenue Technologies Pvt Ltd.", preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "Disagree", style: UIAlertActionStyle.default, handler: nil))
    alert.addAction(UIAlertAction(title: "Agree", style: UIAlertActionStyle.default, handler: self.getvalueoftextfield()))

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

if isValidEmail(emailID: email) == false {
    Error_label.isHidden = false
    Error_label.text = "Please Enter Valid Email Address"
}
else if confirm_email_validation.text == "" {
    Error_label.isHidden = false
    Error_label.text = " Confirm Email Cannot be Empty"
}
else if confirm_email_validation.text != Email_textfield.text{
    Error_label.isHidden = false
    Error_label.text = "Confirm Email Cannot be different"
}
else if confirm_email_validation.text == Email_textfield.text {
    print("email entered correctly")
}



if Choose_Denomination.text == "" && manual_denominaton_textfield.text != ""{

    Choose_Denomination.isUserInteractionEnabled = false

} else if manual_denominaton_textfield.text == "" && Choose_Denomination.text != ""{

    manual_denominaton_textfield.isUserInteractionEnabled = false

}else if manual_denominaton_textfield.text != "" && Choose_Denomination.text != ""{

    Error_label.text = "Choose Denomination and Enter Denomination both Cannot have value"
}





if Choose_Destination.text == "" {
    Error_label.isHidden = false
    Error_label.text = "Choose Destination of Receiver"
}

else if Choose_Denomination.text == "" && manual_denominaton_textfield.text == "" {
    Error_label.isHidden = false
    Error_label.text = "Choose Denomination or Enter Denomination"
}
}