在ViewControllers之间传输TextField数据

时间:2017-07-13 22:25:59

标签: swift swift3 segue ios10 textfield

我有ViewController,它有一个文本字段和一个按钮。用户在文本字段中输入他的名字并点击DONE按钮。当他按下按钮时,他被GifteeDetails视为一个不同的视图控制器。该viewController中有一个标签,可以显示他的名字。但是,他的名字并没有出现。我没有收到错误。

这是ViewController:

@IBOutlet weak var textGifteeName: UITextField!
@IBAction func toDetails(_ sender: Any) {
    performSegue(withIdentifier: "toDetails", sender: nil)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destDetails: GifteeDetails = segue.destination as! GifteeDetails
    destDetails.nametext = textGifteeName.text!
    destDetails.agetext = "\(Int(age)! - 2000 + 17)"
    destDetails.locationstext = labelGifteeLocationsPreview.text!
    destDetails.intereststext = labelGifteeInterestsPreview.text!
}

这是GifteeDetails:

var nametext = String()
var agetext = String()
var locationstext = String()
var intereststext = String()

@IBOutlet weak var labelGifteeName: UILabel!
@IBOutlet weak var labelGifteeAge: UILabel!
@IBOutlet weak var labelGifteeLocations: UILabel!
@IBOutlet weak var labelGifteeInterests: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    nametext = labelGifteeName.text!
    agetext = labelGifteeAge.text!
    locationstext = labelGifteeLocations.text!
    intereststext = labelGifteeInterests.text!
}

抱歉所有的!除非我拥有它们,否则Swift会给我一个错误。

3 个答案:

答案 0 :(得分:0)

您正在更新字符串nametext和其他未与您的标签相关联的字符串。

您需要替换这段代码:

destDetails.nametext = textGifteeName.text!
destDetails.agetext = "\(Int(age)! - 2000 + 17)"
destDetails.locationstext = labelGifteeLocationsPreview.text!
destDetails.intereststext = labelGifteeInterestsPreview.text!

使用:

destDetails.labelGifteeName.text = textGifteeName.text!
destDetails.labelGifteeAge.text = "\(Int(age)! - 2000 + 17)"
destDetails.labelGifteeLocations.text = labelGifteeLocationsPreview.text!
destDetails. labelGifteeInterests.text = labelGifteeInterestsPreview.text!

nametextString个对象,与labelGifteeName.text不同,后者是您要更新的标签的String

答案 1 :(得分:0)

如果你使用segue然后请删除它,然后在FirstviewController中创建该按钮的动作方法,并使用pushViewController在SecondviewController上移动。

Swift 3 例如:

@IBAction func toDetails(_ sender: Any)
{
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "SecondView") as! SecondView

    UserDefaults.standard.set(self. textGifteeName.text, forKey: "savedStringKey")
    UserDefaults.standard.synchronize()
    self.navigationController?.pushViewController(vc,
                                             animated: true)
}

在SecondView中:

override func viewDidLoad() {
    super.viewDidLoad()

    self.labelGifteeName.text = UserDefaults.standard.string(forKey: "savedStringKey")!
}

答案 2 :(得分:0)

请使用 labelGifteeName.text更新 GifteeDetailsVC 中的func viewDidLoad()方法! = nametext labelGifteeAge.text!= agetext 而不是您的代码,因为您已经将值分配给了字符串,即ViewController中的nametext和agetext,您需要在标签中显示字符串值