好的,我對此很陌生,在開發過程中慢慢地工作。但是我意識到如果我能夠解決這個問題,我會有很長的路要走。將IBAction的變量值傳遞給IBOutlet
我打電話給我的服務器上的PHP文件並返回JSON數據。這工作。我可以打印可變
print("firstNameValue: \(firstNameValue)")
我現在想輸出一個變量... firstNameValue的值到名爲文本框的文本字段。
我對Swift很陌生,我在想「全局變量?」。這工作,但我想等待來自HTTP調用的響應來完成然後更新文本字段。
我希望你能幫上忙。我對OOP非常陌生,頭腦破裂。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var feel: UITextField!
@IBAction func anxious(sender: AnyObject) {
let myUrl = NSURL(string: "http://mywebsite.com/Jamesbond.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";// Compose a query string
let postString = "firstName=James&lastName=Bond";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
// Print out response body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
//Let's convert response sent from a server side script to a NSDictionary object:
do {
let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = myJSON {
// Now we can access value of First Name by its key
let firstNameValue = parseJSON["firstName"] as? String
print("firstNameValue: \(firstNameValue)")
EDIT::the below two lines solved it.
dispatch_async(dispatch_get_main_queue()) {
self.textField.text = firstNameValue}
}
} catch {
print(error)
}
}
task.resume()
}
@IBOutlet weak var textField: UITextField!
@IBAction func submit(sender: AnyObject) {
print("hello")
let a = 9
let b = 10
let c = (a*b)
textField.text="You are a banana \(c)"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
只需更換*我想要將此值... *註釋與代碼更新文本字段,你就完成了。 – vadian
謝謝,這不起作用,這是我嘗試的第一件事。 textField.text =「name = \(firstNameValue!)」 這會返回一個錯誤 – uberphoebe
它說我需要把自己。在前面像self.textField.text,但是當我這樣做時,它不會生成編譯錯誤,但沒有值插入字段中。 – uberphoebe