[英]How to update the value of a label.text in swift from within another class
[英]Swift 5 Can't get variable string from a function chosen from pickerview to update Label.text
这是我获取用户生日并转换日期以找到他们的年龄的地方。
//Date Picker
@IBOutlet weak var userBdayLabel: UILabel!
@IBOutlet weak var userBdayPickerScroll: UIDatePicker!
var userBday = ""
//UI BirthdayScroll
@IBAction func userBdayScrollUpdated(_ sender: Any) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
dateFormatter.dateFormat = "MM/dd/yyyy"
let UserBirthday = dateFormatter.string(from: userBdayPickerScroll.date)
userBdayLabel.text = dateFormatter.string(from: userBdayPickerScroll.date)
/// DOB String Entered
let dob : String = UserBirthday
/// Format Date
let myFormatte = DateFormatter()
myFormatte.dateFormat = "MM-dd-yyyy"
/// Convert DOB to new Date
let finalDate : Date = myFormatte.date(from: dob)!
/// Todays Date
let now = Date()
/// Calender
let calendar = Calendar.current
/// Get age Components
let ageComponents = calendar.dateComponents([.year], from: finalDate, to: now)
print("Age is \(ageComponents.year!)")
let userAge = String(ageComponents.year!)
print("User age = \(userAge)")
}
我似乎无法使用IBAction
之外的 UserAge :
将用户的年龄更新为 AgeLabel:
print("Age is \(ageComponents.year!)")
let userAge = String(ageComponents.year!)
print("User age = \(userAge)")
}
这是我想更新的ageLabel
,以使用他们使用我的 PickerView 选择的日期来反映用户的年龄,但我无法通过使用 UserAge 获取他们的年龄来更新 label:
//Results page
//Right Side Label Outlets for Results page
@IBOutlet weak var resultsLabel: UILabel!
@IBOutlet weak var resultView: UIView!
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var genderLabel: UILabel!
@IBOutlet weak var bmiResultsLabel: UILabel!
@IBOutlet weak var drinkingHabits: UILabel!
@IBOutlet weak var smokingHabits: UILabel!
@IBOutlet weak var excerciseLabel: UILabel!
@IBOutlet weak var muscleStrengthLable: UILabel!
@IBOutlet weak var educationLabel: UILabel!
@IBOutlet weak var incomeBracketLabel: UILabel!
@IBOutlet weak var stressLevelsLabel: UILabel!
如果有帮助,这是我的完整代码!
import UIKit
import Firebase
class SignUpViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var userAge: String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//Login screen information
@IBOutlet weak var userFirstNametext: UITextField!
@IBOutlet weak var userLastNametxt: UITextField!
@IBOutlet weak var userEmailtext: UITextField!
@IBOutlet weak var UserEmailText2: UITextField!
@IBOutlet weak var userPasswordText: UITextField!
@IBOutlet weak var userPasswordtext2: UITextField!
@IBOutlet weak var signUpErrorLabel: UILabel!
//submit Login Information Password, Email, First and Last name
@IBAction func createYourAccountButtonPressed(_ sender: Any) {
//delete after testing everything
self.performSegue(withIdentifier: "toVidaClockDescription", sender: nil)
//user name, password and email text field
let userFirstName = userFirstNametext.text
let userLastName = userLastNametxt.text
let userEmail = userEmailtext.text
let userPassword = userPasswordText.text
//Conditions for password *NEEDS WORK DATABASE
if userFirstName != nil && userLastName != nil && userEmail != nil && userPassword == userPasswordtext2.text && userPasswordtext2.text != nil {
print("User first name = \(String(describing: userFirstName))")
print("User last name = \(String(describing: userLastName))")
print("User email = \(String(describing: userEmail))")
print("User password = \(String(describing: userPassword))")
if userEmail!.contains("@") {
Auth.auth().createUser(withEmail: userEmail!, password: userPassword!) { authResult, error in
self.performSegue(withIdentifier: "toVidaClockDescription", sender: nil)
}
}
}
//Tells everyone they are dumb for not knowing how to enter their information
if userFirstName != nil && userLastName != nil && userEmail != nil && userPassword != nil {
self.signUpErrorLabel.text = "Error some of your account information is incorrect. Please fix your information to continue."
print(userFirstName!)
print(userLastName!)
print(userEmail!)
print(userPassword!)
print(userPasswordtext2.text!)
}
}
//Height, Country and Weight Labels and Pickers
@IBOutlet weak var weightCalLabel: UILabel!
@IBOutlet weak var heightbmiLabel: UILabel!
@IBOutlet weak var heightLabel: UILabel!
@IBOutlet weak var heightScrollMenu: UIPickerView!
@IBOutlet weak var weightLabel: UILabel!
@IBOutlet weak var weightScrollMenu: UIPickerView!
@IBOutlet weak var bmiLabel: UILabel!
let heightToInches = (12...90).map { String($0) }
let weightOptions = (50...600).map { String($0) }
var userWeight = 0
var userHeight = 0
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 31 {
return weightOptions.count
}
else{
return heightToInches.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView.tag == 30 {
return "\(heightToInches[row])" + " Inches"
}
else {
return "\(weightOptions[row])" + " Lbs"
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 30 {
heightLabel.text = String(heightToInches[row]) + " Inches"
heightbmiLabel.text = "(Height " + String(heightToInches[row]) + " Inches)²"
userHeight = Int(Double(heightToInches[row])!)
}
if pickerView.tag == 31 {
weightLabel.text = String(weightOptions[row]) + " lbs"
weightCalLabel.text = "Weight " + String(weightOptions[row]) + " lbs"
userWeight = Int(Double(weightOptions[row])!)
}
if userHeight != 0 && userWeight != 0 {
let userBMI = 703 * userWeight / (userHeight * userHeight)
print(userBMI)
if userHeight != 0 && userWeight != 0 {
let userBMI = 703 * userWeight / (userHeight * userHeight)
self.bmiLabel.text = ("= BMI \(userBMI) ")
if userBMI < 18 {
self.bmiLabel.textColor = UIColor.red
self.bmiLabel.text = ("= BMI \(userBMI) ")
}
if userBMI > 18 && userBMI < 25 {
self.bmiLabel.textColor = UIColor.green
self.bmiLabel.text = ("BMI =\(userBMI) ")
}
if userBMI >= 25 && userBMI < 30 {
self.bmiLabel.textColor = UIColor.brown
self.bmiLabel.text = ("= BMI \(userBMI) ")
}
if userBMI > 30 {
self.bmiLabel.textColor = UIColor.red
self.bmiLabel.text = ("= BMI \(userBMI) ")
}
}
}
}
//Date Picker
@IBOutlet weak var userBdayLabel: UILabel!
@IBOutlet weak var userBdayPickerScroll: UIDatePicker!
var userBday = ""
//UI BirthdayScroll
@IBAction func userBdayScrollUpdated(_ sender: Any) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
dateFormatter.dateFormat = "MM/dd/yyyy"
let UserBirthday = dateFormatter.string(from: userBdayPickerScroll.date)
userBdayLabel.text = dateFormatter.string(from: userBdayPickerScroll.date)
/// DOB String Entered
let dob : String = UserBirthday
/// Format Date
let myFormatte = DateFormatter()
myFormatte.dateFormat = "MM-dd-yyyy"
/// Convert DOB to new Date
let finalDate : Date = myFormatte.date(from: dob)!
/// Todays Date
let now = Date()
/// Calender
let calendar = Calendar.current
/// Get age Components
let ageComponents = calendar.dateComponents([.year], from: finalDate, to: now)
print("Age is \(ageComponents.year!)")
let userAge = String(ageComponents.year!)
print("User age = \(userAge)")
}
//Survey Question Number
var questionNumber : Int = 0
let allQuestions = SurveyQuestionBank()
var buttonVisibility : Bool = false
//Survey Questions UILaabels and UIButtons
@IBOutlet weak var surveyQuestionLabel: UILabel!
@IBOutlet weak var option1: UIButton!
@IBOutlet weak var option2: UIButton!
@IBOutlet weak var option3: UIButton!
@IBOutlet weak var option4: UIButton!
@IBOutlet weak var choiceDescriptionLabel: UILabel!
func updateUI() {
option1.setTitle(allQuestions.list[questionNumber].option1Text, for: .normal)
option2.setTitle(allQuestions.list[questionNumber].option2Text, for: .normal)
option3.setTitle(allQuestions.list[questionNumber].option3Text, for: .normal)
option4.setTitle(allQuestions.list[questionNumber].option4Text, for: .normal)
}
//Survey Questions buttons
@IBAction func surveyButtonPressed(_ sender: AnyObject) {
if sender.tag == 1 {
option1.isSelected = true
option2.isSelected = false
option3.isSelected = false
option4.isSelected = false
option2.backgroundColor = UIColor.lightGray
option3.backgroundColor = UIColor.lightGray
option4.backgroundColor = UIColor.lightGray
choiceDescriptionLabel!.text = allQuestions.list[questionNumber - 1].option1Explanation
print("Button 1 Pressed")
}
if sender.tag == 2 {
option1.isSelected = false
option2.isSelected = true
option3.isSelected = false
option4.isSelected = false
option1.backgroundColor = UIColor.lightGray
option3.backgroundColor = UIColor.lightGray
option4.backgroundColor = UIColor.lightGray
choiceDescriptionLabel!.text = allQuestions.list[questionNumber - 1].option2Explanation
print("Button 2 Pressed")
}
if sender.tag == 3{
option1.isSelected = false
option2.isSelected = false
option3.isSelected = true
option4.isSelected = false
option1.backgroundColor = UIColor.lightGray
option2.backgroundColor = UIColor.lightGray
option4.backgroundColor = UIColor.lightGray
choiceDescriptionLabel!.text = allQuestions.list[questionNumber - 1].option3Explanation
print("Button 3 Pressed")
}
if sender.tag == 4 {
option1.isSelected = false
option2.isSelected = false
option3.isSelected = false
option4.isSelected = true
option1.backgroundColor = UIColor.lightGray
option2.backgroundColor = UIColor.lightGray
option3.backgroundColor = UIColor.lightGray
choiceDescriptionLabel!.text = allQuestions.list[questionNumber - 1].option4Explanation
print("Button 4 Pressed")
}
if sender.tag == 10 && questionNumber == 9 {
performSegue(withIdentifier: "surveyResultsSegue", sender: nil)
}
//reset view to not show segue
if sender.tag == 10 && questionNumber == 0 {
performSegue(withIdentifier: "surveyResultsSegue", sender: nil)
option1.backgroundColor = UIColor.lightGray
option2.backgroundColor = UIColor.lightGray
option3.backgroundColor = UIColor.lightGray
option4.backgroundColor = UIColor.lightGray
nextQuestion()
checkAnswerVisibility()
updateUI()
choiceDescriptionLabel.text = ""
questionNumber = 1
}
//if options aren't selected then nothing happens in survey question
else if sender.tag == 10 && option1.isSelected == false && option2.isSelected == false && option3.isSelected == false && option4.isSelected == false {
print("1a")
choiceDescriptionLabel.text = "Whoops! You haven't selected an answer! Please select an answer to continue."
}
//checks to see if option 1 is selcted in view
else if sender.tag == 10 && option1.isSelected == true && option2.isSelected == false && option3.isSelected == false {
print("1a")
option1.backgroundColor = UIColor.lightGray
option2.backgroundColor = UIColor.lightGray
option3.backgroundColor = UIColor.lightGray
option4.backgroundColor = UIColor.lightGray
nextQuestion()
checkAnswerVisibility()
updateUI()
choiceDescriptionLabel.text = ""
questionNumber = questionNumber + 1
option1.isSelected = false
option2.isSelected = false
option3.isSelected = false
option4.isSelected = false
}
else if sender.tag == 10 && option1.isSelected == true && option2.isSelected == false && option3.isSelected == false && option4.isSelected == false {
print("1b")
option1.backgroundColor = UIColor.lightGray
option2.backgroundColor = UIColor.lightGray
option3.backgroundColor = UIColor.lightGray
option4.backgroundColor = UIColor.lightGray
nextQuestion()
checkAnswerVisibility()
updateUI()
choiceDescriptionLabel.text = ""
questionNumber = questionNumber + 1
option1.isSelected = false
option2.isSelected = false
option3.isSelected = false
option4.isSelected = false
}
//checks to see if 2 is selected
else if sender.tag == 10 && option1.isSelected == false && option2.isSelected == true && option3.isSelected == false {
print("2a")
option1.backgroundColor = UIColor.lightGray
option2.backgroundColor = UIColor.lightGray
option3.backgroundColor = UIColor.lightGray
option4.backgroundColor = UIColor.lightGray
nextQuestion()
checkAnswerVisibility()
updateUI()
choiceDescriptionLabel.text = ""
questionNumber = questionNumber + 1
option1.isSelected = false
option2.isSelected = false
option3.isSelected = false
option4.isSelected = false
}
else if sender.tag == 10 && option1.isSelected == false && option2.isSelected == true && option3.isSelected == false && option4.isSelected == false {
print("2b")
option1.backgroundColor = UIColor.lightGray
option2.backgroundColor = UIColor.lightGray
option3.backgroundColor = UIColor.lightGray
option4.backgroundColor = UIColor.lightGray
nextQuestion()
checkAnswerVisibility()
updateUI()
choiceDescriptionLabel.text = ""
questionNumber = questionNumber + 1
option1.isSelected = false
option2.isSelected = false
option3.isSelected = false
option4.isSelected = false
}
//checks to see if 3 is selected
else if sender.tag == 10 && option1.isSelected == false && option2.isSelected == false && option3.isSelected == true {
print("3a")
option1.backgroundColor = UIColor.lightGray
option2.backgroundColor = UIColor.lightGray
option3.backgroundColor = UIColor.lightGray
option4.backgroundColor = UIColor.lightGray
nextQuestion()
checkAnswerVisibility()
updateUI()
choiceDescriptionLabel.text = ""
questionNumber = questionNumber + 1
option1.isSelected = false
option2.isSelected = false
option3.isSelected = false
option4.isSelected = false
}
else if sender.tag == 10 && option1.isSelected == false && option2.isSelected == false && option3.isSelected == true && option4.isSelected == false {
print("3b")
option1.backgroundColor = UIColor.lightGray
option2.backgroundColor = UIColor.lightGray
option3.backgroundColor = UIColor.lightGray
option4.backgroundColor = UIColor.lightGray
nextQuestion()
checkAnswerVisibility()
updateUI()
choiceDescriptionLabel.text = ""
questionNumber = questionNumber + 1
option1.isSelected = false
option2.isSelected = false
option3.isSelected = false
option4.isSelected = false
}
//checks to see if option 4 is selected
else if sender.tag == 10 && option1.isSelected == false && option2.isSelected == false && option3.isSelected == false && option4.isSelected == true {
print("4a")
option1.backgroundColor = UIColor.lightGray
option2.backgroundColor = UIColor.lightGray
option3.backgroundColor = UIColor.lightGray
option4.backgroundColor = UIColor.lightGray
nextQuestion()
checkAnswerVisibility()
updateUI()
choiceDescriptionLabel.text = ""
questionNumber = questionNumber + 1
option1.isSelected = false
option2.isSelected = false
option3.isSelected = false
option4.isSelected = false
}
option1.setTitleColor(.white, for: .selected)
option2.setTitleColor(.white, for: .selected)
option3.setTitleColor(.white, for: .selected)
option4.setTitleColor(.white, for: .selected)
print(questionNumber)
}
func updateAnswerDescription() {
//Gets survey choice description
surveyQuestionLabel!.text = allQuestions.list[questionNumber].questionText
}
//THis just checks if Option Button are visiable or not.
func checkAnswerVisibility() {
//Gets the options text from the Survey Question Bank from swift
let option1Visibility = allQuestions.list[questionNumber].answer1Visibility
let option2Visibility = allQuestions.list[questionNumber].answer2Visibility
let option3Visibility = allQuestions.list[questionNumber].answer3Visibility
let option4Visibility = allQuestions.list[questionNumber].answer4Visibility
option1.isHidden = option1Visibility
option2.isHidden = option2Visibility
option3.isHidden = option3Visibility
option4.isHidden = option4Visibility
}
//UPDATE TEXTs from question bank
func nextQuestion() {
surveyQuestionLabel.font = UIFont.preferredFont(forTextStyle: .body)
surveyQuestionLabel.adjustsFontForContentSizeCategory = true
surveyQuestionLabel!.text = allQuestions.list[questionNumber].questionText
option1.titleLabel!.text = allQuestions.list[questionNumber].option1Text
option2.titleLabel!.text = allQuestions.list[questionNumber].option2Text
option3.titleLabel!.text = allQuestions.list[questionNumber].option3Text
option4.titleLabel!.text = allQuestions.list[questionNumber].option4Text
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
func startOver() {
print("right before startover")
questionNumber = 0
updateUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
class CustomButton: UIButton {
override var isHighlighted: Bool {
didSet {
if (isHighlighted) {
super.isHighlighted = false
titleLabel?.textColor = .white
}
}
}
}
//Results page
//Right Side Label Outlets for Results page
@IBOutlet weak var resultsLabel: UILabel!
@IBOutlet weak var resultView: UIView!
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var genderLabel: UILabel!
@IBOutlet weak var bmiResultsLabel: UILabel!
@IBOutlet weak var drinkingHabits: UILabel!
@IBOutlet weak var smokingHabits: UILabel!
@IBOutlet weak var excerciseLabel: UILabel!
@IBOutlet weak var muscleStrengthLable: UILabel!
@IBOutlet weak var educationLabel: UILabel!
@IBOutlet weak var incomeBracketLabel: UILabel!
@IBOutlet weak var stressLevelsLabel: UILabel!
}
您已经创建了 userAge 变量,只需将您的值存储在该变量中
class SignUpViewController: UIViewController, UIPickerViewDelegate,
UIPickerViewDataSource{
var userAge: String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
像下面这样使用这个变量,并给它赋值。 现在您可以在 Button 操作方法之外使用它的值
print("Age is \(ageComponents.year!)")
userAge = String(ageComponents.year!)
print("User age = \(userAge)")
我通过为每个单独的视图制作单独的视图控制器解决了这个问题
然后通过提供委托来传递每个变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.