Novice coder and I'm stuck. I have 2 UITextField on my Viewcontroller that I want passed to a UITableView when "save" is tapped. I've set both textFields to delegate.self, the problem is that the data entered in the textfields only shows up on the UITableView IF I remove 1 of the UItextFields.
I'm thinking in order to use 2 (or more) UITextFields on the same VC I must need a way besides the outlets to differentiate between them. I've seen responses about tags but I don't understand.
import UIKit
class BudgetViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate {
// Properties:
#IBOutlet weak var datePicker: UIDatePicker!
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var amountTextField: UITextField!
#IBOutlet weak var dateDisplay: UILabel!
#IBOutlet weak var saveButton: UIBarButtonItem!
var budget: Budget?
// Date picker:
let dateFormatter = NSDateFormatter()
func setDate() {
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateDisplay.text = dateFormatter.stringFromDate(datePicker.date)
}
// Navigation
// This method lets you configure a view controller before it's presented
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if saveButton === sender {
let name = nameTextField.text ?? ""
let date = dateDisplay.text ?? ""
let amount = amountTextField.text ?? ""
// set the budget to be passed to the Controller, this code configures the meal prperty with the appropriate values before the segue executes
budget = Budget(date: date, name: name, amount: amount)
}
}
// Actions:
#IBAction func datePickerChanger(sender: AnyObject) {
setDate()
}
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field
nameTextField.delegate = self
amountTextField.delegate = self
}
// UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
}
}
import UIKit
class BudgetTableViewController: UITableViewController {
//Properties
var budgets = [Budget]()
override func viewDidLoad() {
super.viewDidLoad()
loadSampleBudgets()
}
func loadSampleBudgets() {
let budget1 = Budget(date: "8/16/2016", name: "Eyebrows", amount: "15")!
let budget2 = Budget(date: "8/28/2016", name: "Acme", amount: "59")!
let budget3 = Budget(date: "9/10/2016", name: "Wildwood", amount: "199")!
budgets += [budget1, budget2, budget3]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return budgets.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "BudgetTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! BudgetTableViewCell
let budget = budgets[indexPath.row]
cell.dateLabel.text = budget.date
cell.nameLabel.text = budget.name
cell.amountLabel.text = budget.amount
return cell
}
#IBAction func unwindToMealList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.sourceViewController as? BudgetViewController, budget = sourceViewController.budget {
//Add a new meal
let newIndexPath = NSIndexPath(forRow: budgets.count, inSection: 0)
budgets.append(budget)
tableView.insertRowsAtIndexPaths([indexPath], withRowanimation: .Bottom)
}
}
Check to see if your text fields outlets are properly linked to your storyboard. There should be a filled circle next to each IBOutlet. If you have both the code and storyboard open in XCode and hover your mouse over the circle next to each outlet, the text field should highlight on the storyboard.
If you copied and pasted the original name text field and changed it to the amount text field, it actually still might have a reference to the name outlet. You can check this by right clicking on the text field in the storyboard and see what outlets it refers to.
override func viewDidLoad() {
super.viewDidLoad()
nameTextField.delegate = self
streetTextField.delegate = self
cityTextField.delegate = self
stateTextField.delegate = self
countryTextField.delegate = self
phoneTextField.delegate = self
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == nameTextField {
streetTextField.becomeFirstResponder()
}
else if textField == streetTextField {
cityTextField.becomeFirstResponder()
}
else if textField == cityTextField {
stateTextField.becomeFirstResponder()
}
else if textField == stateTextField {
countryTextField.becomeFirstResponder()
}
else if textField == countryTextField {
phoneTextField.becomeFirstResponder()
}
else if textField == phoneTextField {
nameTextField.becomeFirstResponder()
}
return true
}
This is some code I wrote to allow a user to fill in a form (pressing return to move from one field to the next), so you can definitely have multiple textFields with the same delegate.
Related
I want to save the value of filled button(●) into the array "q.answer[indexPath.row]" about each question "q.question[indexPath.row]).
currentQuizButtonIndex is currently renewed every time when ◯ changes to ● by tapping. However, I have no idea how to save in to variable q which is declared in TableViewController.
View Controller display
Code about QuizCell.swift (TableCell which is about 5 buttons and UIlabel.)
import UIKit
import Foundation
protocol QuizCellDelegate {
func quizCellDidChangeCurrentButtonIndex(_ cell: QuizCell, index: Int)
}
class QuizCell: UITableViewCell {
var currentQuizButtonIndex: Int = 0 {
didSet {
let value = self.currentQuizButtonIndex
self.updateCurrentQuizButton(value)
if let delegate = self.delegate {
delegate.quizCellDidChangeCurrentButtonIndex(self, index: value)
}
}
}
#IBOutlet weak var questionLabel: UILabel!
#IBOutlet var answerButtons: [UIButton]!
var delegate: QuizCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
//print("ここまできてるか確認")
// Initialization code
}
#IBAction func didTapQuizButton(_ sender: UIButton) {
if let index = self.answerButtons.firstIndex(of: sender){
self.currentQuizButtonIndex = index
delegate?.quizCellDidChangeCurrentButtonIndex(self, index: index)
print(index)
}
}
private func updateCurrentQuizButton(_ currentIndex: Int){
for (index, answerButton) in self.answerButtons.enumerated(){
if index == currentIndex {
answerButton.setTitle("●", for: .normal)
} else {
answerButton.setTitle("○", for: .normal)
}
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Code about View Controller
import UIKit
class AnswerQuizViewController: UIViewController, UITableViewDelegate {
var q: QuestionSeries!
#IBOutlet weak var quizTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
quizTableView.dataSource = self
quizTableView.delegate = self
// cell xibファイルを使うときは書く必要があるやつ。
// quizTableView.register(UINib(nibName: K.Cells.QuizCellNibName, bundle: nil), forCellReuseIdentifier: K.Cells.QuizCellIdentifier)
quizTableView.register(UINib(nibName: "QuizCell", bundle: nil), forCellReuseIdentifier: "QuizCellIdentifier")
// Do any additional setup after loading the view.
}
// 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.
//// if segue.identifier == K.Segue.checkResult {
//// let resultViewController = segue.destination as! ResultViewController
//// answerQuizViewController.q =
//// print(answerQuizViewController.q)
// }
}
// MARK: - quizTableViewのアレンジ
extension AnswerQuizViewController: UITableViewDataSource, QuizCellDelegate {
func quizCellDidChangeCurrentButtonIndex(_ cell: QuizCell, index: Int) {
if let indexPath = self.quizTableView.indexPath(for: cell){
self.q.question[indexPath.row].answer = index
print(index)
}else{
print("ここきてます")
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return q.question.count
//print(q.question.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let question = q.question[indexPath.row]
let cell = quizTableView.dequeueReusableCell(withIdentifier: K.Cells.QuizCellIdentifier, for: indexPath) as! QuizCell
cell.questionLabel.text = question.text
// print(question.text)
return cell
}
}
It is also helpful if you have any idea of implementing this by alternative way.
Thanks.
How about you create a static array and store your data into that array.
when the button is tapped you can append it into that static array.
Create a new file. Just a basic "Swift file".
struct structName {
static var qArray: [String] = []
}
Then append data by:
structName.q.append()
Finally get your data trough:
structName.q[index]
I have a ViewController which uses multiple Subviews (HomeViewController, etc.) which can be selected via a Custom Tab Bar at the bottom of my app. Inside the HomeViewController there is a UIView containing a UITableView containing a Prototype Custom Cell with name and image.
import UIKit
class HomeViewController: UIViewController {
#IBOutlet weak var friendView: UITableView!
let friends = ["batman", "harsh", "ava", "sasha", "fatima", "alfred"]
override func viewDidLoad() {
super.viewDidLoad()
friendView.delegate = self
friendView.dataSource = self
friendView.allowsSelection = false
}
}
extension HomeViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friends.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = friendView.dequeueReusableCell(withIdentifier: "customCell") as! CustomCell
let friend = friends[indexPath.row]
cell.avatarImg.image = UIImage(named: friend)
cell.nameLbl.text = friend
return cell
}
}
Custom cell:
import UIKit
class CustomCell: UITableViewCell {
#IBOutlet weak var friendView: UIView!
#IBOutlet weak var nameLbl: UILabel!
#IBOutlet weak var avatarImg: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
When I start the app, everything looks just fine. However, when I start scrolling inside the table, all data suddenly disappears. All relations between storyboard and code should be just fine. I think it might have got something to do with my need of using a Subview.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tabBarView: UIView!
#IBOutlet weak var contentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
Design.makeCornersRound(view: tabBarView, radius: 10.0)
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { (timer) in
self.switchToHomeViewController()
}
}
#IBAction func onClickTabBar(_ sender: UIButton) {
let tag = sender.tag
if tag == 1 {
switchToIncomingsViewController()
}
else if tag == 2 {
switchToSpendingsViewController()
}
else if tag == 3 {
switchToHomeViewController()
}
else if tag == 4 {
switchToSavingsViewController()
}
else if tag == 5 {
switchToSettingsViewController()
}
}
func switchToHomeViewController() {
guard let Home = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as? HomeViewController else { return }
contentView.addSubview(Home.view)
Home.didMove(toParent: self)
}
...
}
Reference to the tutorial I have been trying to implement: https://www.youtube.com/watch?v=ON3Z0PXSoVk
In this function:
func switchToHomeViewController() {
// 1
guard let Home = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as? HomeViewController else { return }
// 2
contentView.addSubview(Home.view)
// 3
Home.didMove(toParent: self)
// 4
}
At 1 you create an instance of HomeViewController
at 2 you add its view to cotentView
at 3 you call didMove() ... but that doesn't do anything because you haven't added the controller to your hierarchy
at 4 your Home instance goes away, so the code in that controller no longer exists
You need to add the controller as a child controller.
As a side note, use lowerCase for variable names:
func switchToHomeViewController() {
// create an instance of HomeViewController
guard let homeVC = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as? HomeViewController else { return }
// add it as a child view controller
self.addChild(homeVC)
// add its view
contentView.addSubview(homeVC.view)
// here you should either set the view's frame or add constraints
// such as:
homeVC.view.frame = contentView.bounds
// inform the controller that it moved to a parent controller
homeVC.didMove(toParent: self)
}
it is my first time using segment control and realm. so currently I am using segue to perform segue to Add/EditVC for modification of data.
when segue performed and took data to Add/EditVC to variable selectedTransaction, I want as following data to to be filled accordingly
/* selectedTransaction print statement Results */
print("selectedTransaction = \(selectedTransaction!)")
selectedTransaction = Transaction {
categoryType = Category {
type = expense;
name = EXPENSE 3;
};
amount = 1000;
date = April 2;
}
amountTF.text = selectedTransaction.amount (done and correct)
categorySCoutlet.selectedSegmentIndex = selectedTransaction.categoryType.type (fail to show segmentindex at selectedTransaction.categoryType.type)
categoryTF.text = selectedTransaction.categoryType.name (name shown correctly, however will return nil if user did not RESELECT again)
I was expecting all data are shown as if it created.
However, I faced 2 issue in getting it done
SegmentControl selected index are always in 0 instead of selectedTransaction.categoryType.name (I want the segment control to be at the index which is as created)
categoryTF.text are showing correctly, but if I did not choose again and leave as it be. It will auto return back to nil in results when I pressed the saveButton. : I wish categoryTF.text will return as created and value will not change even if I did not touch it and clicked saveButton
In gif shown below, I chosen row2 as sample. and the result in Realm Browser showing as it is.
I only changed the amountTF.text information from 1200 to 2000, which in result realm browser will set the result of cateogoryType in segmentcontrol to "income" and category will return to nil
sample of the workflow
//Data Model
//MARK: - Transaction Category Section
enum CategoryType : String, CaseIterable {
case income = "income"
case expense = "expense"
init?(id : Int) {
if id < CategoryType.allCases.count {
self = CategoryType.allCases[id]
} else {
return nil
}
}
}
class Category : Object {
#objc dynamic var type : String = CategoryType.income.rawValue
#objc dynamic var name : String = ""
// let parentCategory = LinkingObjects(fromType: Transaction.self, property: "ofCategory")
convenience init(type:CategoryType, name: String) {
self.init()
self.type = type.rawValue
self.name = name
}
}
/* VC that should read and load all data to required place */
//edit
var selectedTransaction : Transaction!
#IBOutlet weak var amountTF: UITextField!
//PickerView for keyboard
lazy var pickerView : UIPickerView = UIPickerView()
//Segment Control
#IBOutlet weak var categorySCoutlet: UISegmentedControl!
#IBOutlet weak var categoryTF: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
amountTF.text! = selectedTransaction.amount
categoryTF.text! = selectedTransaction.categoryType!.name
setupPicker()
}
#IBAction func categoryTypeSC(_ sender: UISegmentedControl) {
guard let type = CategoryType(id: sender.selectedSegmentIndex) else {
fatalError("error")
}
currentCategories = categories.filter("type == %#", type.rawValue)
categoryTF.text = currentCategories.first?.name
pickerView.reloadAllComponents()
pickerView.selectRow(1, inComponent: 0, animated: true)
}
//MARK:- Add Transaction Btn
#IBAction func addTransButtonTapped(_ sender: UIButton) {
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if touches.first?.view == view {
categoryTF.resignFirstResponder()
}
}
//MARK:- Picker Helper
func setupPicker() {
currentCategories = categories.filter("type == %#", CategoryType.income.rawValue)
categoryTF.inputView = pickerView
pickerView.delegate = self
pickerView.dataSource = self
categorySCoutlet.setTitle("Income", forSegmentAt: 0)
categorySCoutlet.setTitle("Expense", forSegmentAt: 1)
categorySCoutlet.addTarget(self, action: #selector(categoryTypeSC(_:)), for: .valueChanged)
}
You are calling tableView.deselectRow(at: indexPath, animated: false) in your tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) method.
This results in returning the incorrect indexPath in prepareForSegue.
You should either remove the deselectRow call from didSelectRowAtIndexPath method,
or you should create a property to hold the value of indexPath.
Something like this:
// somewhere in your class
var selectedIndexPath: IndexPath?
then
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedRowForTrans : Transaction = getTransactions[indexPath.row]
selectedIndexPath = indexPath // set the value of selectedIndexPath
tableView.deselectRow(at: indexPath, animated: false)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "editTrans") {
if let indexPath = selectedIndexPath { // check if there is a valid indexPath
let editTransVC = segue.destination as! AddTransactionTableViewController
let selectedRowForTrans : Transaction = getTransactions[indexPath.row]
editTransVC.selectedTransaction = selectedRowForTrans
}
}
}
Hope this helps
This question already has answers here:
Get button's row in view based table
(5 answers)
Closed 4 years ago.
I'm learning Cocoa in Swift. I created a NSTableView with Viewbased.
Simple tableview
I also connected the checkbox action to ViewController. But when I clicked the checkbox, it printed -1 instead of the row index. I have to select the row first then click the checkbox to get the right index number. Are there anyway to get the row index with every single checkbox or button on each row? Here is my code:
import Cocoa
let data: [String] = ["Apple", "Microsoft", "IBM", "Tesla", "SpaceX",
"Boeing" , "Nasa"]
class ViewController: NSViewController, NSTableViewDelegate,
NSTableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
self.table.delegate = self
self.table.dataSource = self
self.table.reloadData()
// Do any additional setup after loading the view.
}
#IBOutlet weak var table: NSTableView!
#IBAction func CheckClicked(_ sender: Any) {
print(self.table.selectedRow)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func numberOfRows(in tableView: NSTableView) -> Int {
return data.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn:
NSTableColumn?, row: Int) -> NSView? {
if (tableColumn?.identifier)!.rawValue == "NameColumn"
{
if let cell = tableView.makeView(withIdentifier:
NSUserInterfaceItemIdentifier(rawValue: "NameColumn"), owner: self)
as? NSTableCellView
{
cell.textField?.stringValue = data[row]
return cell
}
}
else if (tableColumn?.identifier)!.rawValue == "CheckColumn"
{
if let cell = tableView.makeView(withIdentifier:
NSUserInterfaceItemIdentifier(rawValue: "CheckColumn"), owner: self)
as? NSButton
{
return cell
}
}
return nil
}
func tableViewSelectionDidChange(_ notification: Notification) {
print(self.table.selectedRow)
}
}
This is what you are looking for, but a better implementation would be to use the action with a NSTableCellView subclass.
#IBAction func CheckClicked(_ sender: NSButton) {
// print(self.table.selectedRow)
let row = table.row(for: sender)
print("Button row \(row)")
}
I can only create a subclass based on NSButton.
class myCustomView: NSButton{
#IBOutlet weak var CheckButton: NSButtonCell!
}
Although I can't change the title of these button cell.
if (tableColumn?.identifier)!.rawValue == "CheckColumn"
{
if let cell = tableView.makeView(withIdentifier:
NSUserInterfaceItemIdentifier(rawValue: "CheckColumn"), owner: self)
as? myCustomView
{
cell.CheckButton.title = data[row]
return cell
}
}
I don't know why Xcode doens't let me create a subclass based on NSTableCellView.
when I would like to make the data from the valise, table view controller (SelectedCity) ,app crash and error : Thread1: EXC_BAD_ACCESS (code=1, address 0x…)
error is in line labelcity!.text = tit varibale tit not problem ,I think the problem lies in the UIlabel (labelcity)
can you help me?
AircraftSearch
class AircraftSearch: UIViewController ,SendbackDelegate{
#IBOutlet weak var Mabda: UIButton!
#IBOutlet weak var maghsad: UIButton!
#IBOutlet weak var labelcity: UILabel!
var Airurl = NSURL()
var ScrOrDstArray = [MabdaAndMaghsad]()
var origin = [String]() // save mabda
var purpose = [String]() // save maghsad
var sendDataToTableview = [String]()
var tit = String()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
GetPassCity()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func selectMabda(sender: AnyObject) {
sendDataToTableview = origin
performSegueWithIdentifier("SelectedCellSegue", sender: sender)
}
#IBAction func selectMaghsad(sender: AnyObject) {
sendDataToTableview = purpose
print(sendDataToTableview)
performSegueWithIdentifier("SelectedCellSegue", sender: sender)
}
func originAndpurpose() {
let dataCity = ScrOrDstArray
for i in dataCity{
if i.SrcOrDst == true{
origin.append(i.Name)
}else{
purpose.append(i.Name)
}
}
}
func sendNameToPreviousVC(SelectCity: String) {
print("\(tit) selected ") //return data
tit = SelectCity
labelcity!.text = tit
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SelectedCellSegue" {
if let VC = segue.destinationViewController as? SelectedCity {
VC.toTake = sendDataToTableview
VC.delegate = self
}
}
}
}
SelectedCity view
import UIKit
protocol SendbackDelegate:class {
func sendNameToPreviousVC(City:String)
}
class SelectedCity: UITableViewController {
var toTake = [String]()
var selecteCity = String()
weak var delegate: SendbackDelegate? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return toTake.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("stcell", forIndexPath: indexPath) as? mAndMCell
let nameCity = toTake[indexPath.row]
print(nameCity)
cell!.nameCityLabel.text = nameCity
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! mAndMCell!
selecteCity = currentCell.nameCityLabel!.text as String!
sendBackIdCity(selecteCity)
navigationController?.popViewControllerAnimated(true)
}
func sendBackIdCity(name: String){
self.delegate?.sendNameToPreviousVC(name)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "backCitySegue"{
var VCOne = segue.destinationViewController as? AircraftSearch
self.delegate = VCOne
}
}
}
Instead of
#IBOutlet weak var labelcity: UILabel? = UILabel()
try:
#IBOutlet weak var labelcity: UILabel!
Consider to remove weak keyword in the property declaration. Usage of this keyword prevents just created UILabel object from it's retaining, so the object deallocates immediately.
var labelcity: UILabel? = UILabel()
Or another option is to move object instantiation into viewDidLoad method:
var labelcity: UILabel!
...
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel()
//you code for subview adding into view controller's view
labelcity = label
GetPassCity()
}
I solved the problem:
override func viewDidLoad() {
super.viewDidLoad()
labelcity.text = tit
GetPassCity()
}
func sendNameToPreviousVC(SelectCity: String) {
tit = SelectCity
}