textFieldDidBeginEditing:在展开Optional值时意外发现nil

时间:2016-06-10 13:23:39

标签: ios swift2 textfield

我希望切换键盘时视图向上移动。它适用于我所有的其他观点,但在这一点中它不起作用。它说"unexpectedly found nil while unwrapping an Optional value"

这是我的代码:

class SecondViewController: UIViewController , UIPickerViewDelegate, UIPickerViewDataSource{


@IBOutlet var ScrollView: UIScrollView!
@IBOutlet weak var codeaffiche: UILabel!

@IBOutlet var Prix: UITextField!
@IBOutlet var NomProduit: UITextField!
@IBOutlet var picker1: UIPickerView!
@IBOutlet var NomMAG: UITextField!
var nom_magasin :String!
var pickerData = [String]()
var pickerDataRow = [String]()
override func viewDidLoad() {
    super.viewDidLoad()
    codeaffiche.text = detectionString 

    NomMAG.alpha = 0
    let str = "http://vps43623.ovh.net/yamoinscher/api/getAllMag"
    let url = NSURL(string: str)!

    let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
        if let urlContent = data {
            do {
                let jsonObject = try NSJSONSerialization.JSONObjectWithData(urlContent, options: [])
                if let jsonResult = jsonObject as? [String:AnyObject],
                    magasin = jsonResult["magasin"] as? [[String:String]] {
                        // filter valid items, map them to an array and filter empty strings
                        self.pickerData = magasin.filter { $0["libelle"] != nil }.map { $0["libelle"]! }.filter { !$0.isEmpty}
                        self.pickerDataRow = magasin.filter { $0["id"] != nil }.map { $0["id"]! }.filter { !$0.isEmpty}
                    self.pickerData.append("choisir magasin")
                }
                dispatch_async(dispatch_get_main_queue()) {

                    self.picker1.reloadAllComponents()
                }
            } catch {
                print("JSON serialization failed", error)
            }
        } else if let connectionError = error {
            print("connection error", connectionError)
        }

    }

    task.resume()

}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    ScrollView.keyboardDismissMode = .OnDrag

}
func textFieldShouldReturn(textField: UITextField) -> Bool {

    textField.resignFirstResponder()
    return true
}
func textFieldDidBeginEditing(textField: UITextField) {

    if textField ==  NomMAG {

    ScrollView.setContentOffset(CGPointMake(0, 250), animated: true)
    }
}
func textFieldDidEndEditing(textField: UITextField) {
     if textField ==  NomMAG {
    ScrollView.setContentOffset(CGPointMake(0,0), animated: true)
    }
}



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

// The number of columns of data
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

// The number of rows of data
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return self.pickerData.count
}

// The data to return for the row and component (column) that's being passed in


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

    return self.pickerData[row]
}


func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {



    if pickerData[row] == "choisir magasin"
    {
        //print(row)

        NomMAG.alpha = 1
        nom_magasin = NomMAG.text
    }
    else
    {
        //print(row.description)
        NomMAG.alpha = 0
        nom_magasin = pickerData[row]
    }



}


@IBAction func AddProduct(sender: AnyObject) {

    let myUrl = NSURL(string: "http://vps43623.ovh.net/yamoinscher/ios/products/addIos");let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST";
    // Compose a query string
    let postString = "code_barre=\(detectionString!)&&libelle=\(NomProduit.text!)&nom_magasin=\(nom_magasin!)&prix=\(Prix.text!)"
    let postLength = String(postString.characters.count)

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    request.setValue(postLength, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {

        data, response, error in

        if error != nil
        {
            print("error=\(error)")
            return
        }

        // print out response object
        print("response = \(response)")

        // Print out response body
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")


    }
    task.resume()

}

}

0 个答案:

没有答案