Why are my buttons preferences/parameters resetting when I change view? - ios

I have this iOS application where the value from cells in a tableview is used to set the preferences/parameters on my UIButtons.
When the button is pressed I send with it the tag ID to the tableview, when the user press a cell it collects both text and image and return it (along with the tag ID) back to the main view.
This successfully changes the parameters on the button with the corresponding button tag ID, but when I now press a new button to do the same procedure it resets the first button changes (clears the image and text) and just applies changes to the new button that is pressed.
This is the main view controller class:
class ViewController: UIViewController {
var recievedItem: ChosenItem?
var imageToButton: UIImage?
#IBOutlet weak var button1: UIButton!
#IBOutlet weak var button2: UIButton!
#IBOutlet weak var button3: UIButton!
func AddNew() {
performSegueWithIdentifier("addNew", sender: nil)
}
#IBAction func loadItem(sender: UIButton!) {
performSegueWithIdentifier("itemList", sender: sender)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "itemList"){
let tableViewController : TableViewController = segue.destinationViewController as! TableViewController
tableViewController.buttonTag = sender!.tag
}
}
#IBAction func play(sender: UIButton) {
print("Jeg har fått \(recievedItem!.chosenWord)")
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.translucent = true
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Open", style: .Plain, target: self, action: "AddNew")
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "AddNew")
if(recievedItem != nil){
imageToButton = UIImage(data: recievedItem!.chosenImage)
switch recievedItem!.chosenButton{
case 0:
button1.setBackgroundImage(imageToButton, forState: .Normal)
button1.setTitle(recievedItem!.chosenWord, forState: .Normal)
case 1:
button2.setBackgroundImage(imageToButton, forState: .Normal)
button2.setTitle(recievedItem!.chosenWord, forState: .Normal)
case 2:
button3.setBackgroundImage(imageToButton, forState: .Normal)
button3.setTitle(recievedItem!.chosenWord, forState: .Normal)
default:
print("No buttonTag recieved")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is the tableview class:
class TableViewController: UITableViewController {
var words = [Words]()
var chosenItem: ChosenItem!
var buttonTag: Int!
override func viewDidLoad() {
super.viewDidLoad()
let appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context: NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "Words")
request.returnsObjectsAsFaults = false
do {
words = try context.executeFetchRequest(request) as! [Words]
} catch {
print("Unresolved error")
abort()
}
print("Her er også button tag \(buttonTag)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.words.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let itemWord = self.words[indexPath.row]
cell.textLabel?.text = itemWord.word
cell.imageView?.image = UIImage(data: itemWord.image!)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print(self.words[indexPath.row].word!)
chosenItem = ChosenItem()
chosenItem.chosenButton = buttonTag
chosenItem.chosenWord = self.words[indexPath.row].word!
chosenItem.chosenImage = self.words[indexPath.row].image!
performSegueWithIdentifier("backToMain", sender: chosenItem)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "backToMain"){
let mainViewController : ViewController = segue.destinationViewController as! ViewController
let data = sender as! ChosenItem
mainViewController.recievedItem = data
}
}
}
This is the model class that holds the data:
class ChosenItem: NSObject {
var chosenButton: Int!
var chosenWord: String!
var chosenImage: NSData!
}

The problem is this line:
performSegueWithIdentifier("backToMain", sender: chosenItem)
That is not how you return from a pushed-or-presented view controller to the view controller that pushed-or-presented it! What you are doing is creating a completely new view controller, and that's why the chosen button is not set; it is a different view controller with a different chosen button, namely none because this view controller has just come into existence.
Not only will this mess things up with the chosen button, but eventually your app will crash because you are creating one view controller on top of another every time you go forward and back, and eventually you'll run out of memory.
The way to get back from a pushed view controller is popViewController. The way to get back from a presented view controller is dismissViewController.
If you know what you're doing, you can instead use a special non-segue segue called an unwind segue, but it doesn't sound like you're ready to do that.

Related

swift: segue on button click

I want to move to the next controller on button click with using segue. I need to get number of press button in next controller.
This is code from my controller:
import UIKit
class ViewController2: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var tblTable: UITableView!
var buttonTitles = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"]
override func viewDidLoad() {
super.viewDidLoad()
tblTable.delegate = self
tblTable.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return buttonTitles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "buttoncell") as! ButtonCell
let buttonTitle: String = buttonTitles[indexPath.row]
cell.btnButton.setTitle(buttonTitle, for: .normal)
cell.btnButton.tag = indexPath.row
cell.btnButton.addTarget(self, action: #selector(self.buttonClick(button:)), for: .touchUpInside)
cell.selectionStyle = .none
return cell
}
#objc func buttonClick(button: UIButton) -> Void {
print("btnButton clicked at index - \(button.tag)")
button.isSelected = !button.isSelected
if button.isSelected {
button.backgroundColor = UIColor.green
} else {
button.backgroundColor = UIColor.yellow
}
}
}
class ButtonCell: UITableViewCell {
#IBOutlet var btnButton: UIButton!
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
btnButton.backgroundColor = UIColor.green
} else {
btnButton.backgroundColor = UIColor.yellow
}
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
if highlighted {
btnButton.backgroundColor = UIColor.green
} else {
btnButton.backgroundColor = UIColor.yellow
}
}
}
How to solve the problem it with my code?
It's very simple.
Follow these steps to create segue from your tableview cell button (click).
Open your storyboard layout (view controller)
Add new (destination) view controller.
Select your button.
Press & hold control ctrl button from keyboard and drag mouse cursor from your button to new (destination) view controller.
Now add following code to your source view controller file (source code)
-
override func performSegue(withIdentifier identifier: String, sender: Any?) {
print("segue - \(identifier)")
if let destinationViewController = segue.destination as? <YourDestinationViewController> {
if let button = sender as? UIButton {
secondViewController.<buttonIndex> = button.tag
// Note: add/define var buttonIndex: Int = 0 in <YourDestinationViewController> and print there in viewDidLoad.
}
}
}
Another way to handle the same.
You need to use performSegueWithIdentifier("yourSegue", sender: sender) to segue on an event. This takes in your segue identifier in place of "yourSegue".
This will go in the func that you call when the user presses the button. If you need to send the amount of button clicks to the new View Controller then I would do something similar to this:
let secondViewController = segue.destination as! ViewController
secondViewController.buttonClicks = myButtonClicks

Reload View from Modal View Controller with CoreData in Xcode

I was following a YouTube tutorial on how to create a to-do list with CoreData and my app can build and run however instead of using another view controller to create a task, I created a modal view controller to be displayed over the regular view controller. The problem is it saves it to the CoreData but only displays when the app is reset, this is all the code used for the regular view controller where the tasks should appear:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableViewTest: UITableView!
var tasks : [Task] = []
override func viewDidLoad() {
super.viewDidLoad()
tableViewTest.dataSource = self
tableViewTest.delegate = self
self.navigationController?.isNavigationBarHidden = true
}
override func viewWillAppear(_ animated: Bool) {
getData()
tableViewTest.reloadData()
}
func tableView(_ tableViewTest: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
func tableView(_ tableViewTest: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let task = tasks[indexPath.row]
cell.textLabel?.text = task.name!
return cell
}
func getData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
tasks = try context.fetch(Task.fetchRequest())
}
catch {
print("Fetch Error")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
and this is the code for the modal view controller where the user enter is information to be saved to CoreData:
class popVCAdd: UIViewController {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var popViewAc: UIView!
override func viewDidLoad() {
super.viewDidLoad()
popViewAc.layer.cornerRadius = 20
popViewAc.layer.masksToBounds = true
let toolbar = UIToolbar()
toolbar.sizeToFit()
textField.inputAccessoryView = toolbar
let keyboardDone = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.disappearKey))
toolbar.setItems([keyboardDone], animated: false)
}
#IBAction func doneBtn(_ sender: Any) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let task = Task(context: context)
task.name = textField.text!
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
#IBAction func dismissPop(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
func disappearKey() {
view.endEditing(true)
}
}
Does anybody know what's wrong with it?
Please Change you ModalPresantaion Style to Full Screen
See Below Screen Shot:
Select Segue First:
Change Its Presantation Style to Full Screen:
I am Suggesting you above changes because:
viewWillAppear of your ViewController is not calling after Dismissing from your popVCAdd Controller.

Bar Button Nil After Pressing Switch in Swift?

Ok here is what is going on. I have a table view class called MainTabeViewController. I have a sidebar class called SettingsSidebarViewController that uses SW Reveal to show a menu. The menu is toggled by a bar button item called settings. The menu works fine with the bar button item, and when you press it the menu toggles like it should.
However, once I click a switch, the app crashes and I start getting a EXC_BAD_INSTRUCTION error that reads in the console Fatal error: unexpectedly found nil while unwrapping an optional value. Why is the bar button item suddenly nil after the switch is pressed?
MAINTABLEVIEWCONTROLLER.swift
import UIKit
import SwiftyJSON
class MainTableViewController: UITableViewController, SettingsSidebarViewDelegate {
//HEERE IS THE BAR BUTTON ITEM CALLED SETTINGS <- <- <-
#IBOutlet var settings: UIBarButtonItem!
var NumberofRows = 0
var names = [String]()
var descriptions = [String]()
var categories = [String]()
var types = [String]()
var series = [String]()
var groups = [String]()
func parseJSON(){
let path = NSBundle.mainBundle().URLForResource("documents", withExtension: "json")
let data = NSData(contentsOfURL: path!) as NSData!
let readableJSON = JSON(data: data)
NumberofRows = readableJSON["Documents"].count
for i in 1...NumberofRows {
let doc = "Doc" + "\(i)"
let Name = readableJSON["Documents"][doc]["name"].string as String!
let Description = readableJSON["Documents"][doc]["description"].string as String!
let Category = readableJSON["Documents"][doc]["category"].string as String!
let Type = readableJSON["Documents"][doc]["type"].string as String!
let Series = readableJSON["Documents"][doc]["tags"]["series"].string as String!
let Group = readableJSON["Documents"][doc]["tags"]["group"].string as String!
names.append(Name)
descriptions.append(Description)
categories.append(Category)
types.append(Type)
series.append(Series)
groups.append(Group)
}
}
Here is where the errors start to occur AFTER the switch is pressed (still in same class)
func initSettings(){
//Sets button title to gear, sets button actions (to open menu)
settings.title = NSString(string: "\u{2699}\u{0000FE0E}") as String!
let font = UIFont.systemFontOfSize(25);
settings.setTitleTextAttributes([NSFontAttributeName: font], forState:UIControlState.Normal)
settings.target = self.revealViewController()
settings.action = #selector(SWRevealViewController.rightRevealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
func showTags(showTags: Bool) {
tableView.reloadData()
}
func showTimestamp(showTimeStamp: Bool) {
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
parseJSON()
initSettings()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return NumberofRows
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MainTableCell", forIndexPath: indexPath) as! MainTableViewCell
if names.count != 0{
cell.fileName.text = names[indexPath.row]
cell.fileDescription.text = descriptions[indexPath.row]
cell.fileCategory.text = categories[indexPath.row]
cell.fileType.text = types[indexPath.row]
cell.options.setTitle(NSString(string: ":") as String!, forState: .Normal)
cell.tag1.text = series[indexPath.row]
cell.tag2.text = groups[indexPath.row]
if showTagsVal{
cell.tag1.hidden = false
}
else{
cell.tag1.hidden = true
}
if showTimeStampVal{
cell.tag2.hidden = false
}
else{
cell.tag2.hidden = true
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("showView", sender: self)
}
// MARK: - Navigation
//In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "showView"){
let detailVC: DetailViewController = segue.destinationViewController as! DetailViewController
let indexPath = self.tableView.indexPathForSelectedRow!
detailVC.text = names[indexPath.row]
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}}}
SettingsSidebarViewController.swift
import UIKit
protocol SettingsSidebarViewDelegate{
func showTags(showTags: Bool);
func showTimestamp(showTimeStamp: Bool)
}
var showTagsVal = false
var showTimeStampVal = false
class SettingsSidebarViewController: UIViewController {
var delegate: SettingsSidebarViewDelegate! = nil
#IBOutlet weak var sidebar_title: UILabel!
#IBOutlet var showTagsSwitch: UISwitch!
#IBOutlet var showTimestampSwitch: UISwitch!
#IBAction func switchPressed(sender: AnyObject) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("main") as! MainTableViewController
self.presentViewController(nextViewController, animated:true, completion:nil)
let vc = MainTableViewController()
self.delegate = vc
if showTagsSwitch.on{
showTagsVal = true
delegate.showTags(showTagsVal)
}
else{
showTagsVal = false
delegate.showTags(showTagsVal)
}
if showTimestampSwitch.on{
showTimeStampVal = true
delegate.showTimestamp(showTimeStampVal)
}
else{
showTimeStampVal = false
delegate.showTimestamp(showTimeStampVal)
}
}
override func viewDidLoad() {
super.viewDidLoad()
sidebar_title.text = "Settings"
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
Help is appreciated! I am sure this is a question concerning transitioning view controllers that is something easy but I have tried too long to figure it out.
Your problem is you are creating a new instance of MainTableViewController and assigning it to delegate. That's why the bar button item is nil, because all the initialization and binding isn't done.
You have to change the delegate and assign the view controller you already got with instantiateViewControllerWithIdentifier:
self.delegate = nextViewController

Why is my tableViewController not loading any data?

Im creating an app where different buttons in a ViewController load different menu's into the tableViewController. The buttons are linked by a prepare for segue and the menu's (arrays) are linked by a contentMode. 1: breakfast menu & 2: lunch menu. I had allot of help from someone setting this up but now the table is not loading any data... The cell has 3 labels which display an item, info and price. It changes value within the code when a contentMode is selected. Does anyone see the problem in my code? thanks a lot!
import UIKit
class foodMenuController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let foodMenuController = segue.destinationViewController as! foodTableViewController
if segue.identifier == "showBreakfast" {
foodMenuController.contentMode = 1
} else if segue.identifier == "showLunch" {
foodMenuController.contentMode = 2
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import UIKit
class foodTableViewCell: UITableViewCell {
#IBOutlet weak var foodItem: UILabel!
#IBOutlet weak var foodDescription: UILabel!
#IBOutlet weak var foodPrice: UILabel!
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
}
}
import UIKit
class foodTableViewController: UITableViewController {
//Content Mode Selection in menu
var contentMode = 0
// THIS SHOULD BE LOADED WHEN CONTENT MODE is "1" --> BREAKFAST
let breakfastItems = ["Bread", "Coffee", "Nada"]
let breakfastInfo = ["Good", "Nice", "Nothing"]
let breakfastPrice = ["$1", "$100", "$12,40"]
// THIS SHOULD BE LOADED WHEN CONTENT MODE IS "2" --> LUNCH
let lunchItems = ["Not bread", "Not Coffee", "Something"]
let lunchInfo = ["Not good", "Not nice", "Yes"]
let lunchPrice = ["$1", "$100", "$12,40"]
var foodItems: [String] = []
var foodInfo: [String] = []
var foodPrice: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
switch (contentMode){
case 1: contentMode = 1
foodItems = breakfastItems
foodInfo = breakfastInfo
foodPrice = breakfastPrice
case 2: contentMode = 2
foodItems = lunchItems
foodInfo = lunchInfo
foodPrice = lunchPrice
default:
break
}
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
return foodItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! foodTableViewCell
cell.foodItem.text = foodItems[indexPath.row]
cell.foodDescription.text = foodInfo[indexPath.row]
cell.foodPrice.text = foodPrice[indexPath.row]
return cell
}
}
There isn't anything apparently wrong with the snippet you shared. You can check what is returned in the tableView:numberOfRowsInSection: method and see if it is returning a value > 0
Also, this is a given but we've all done it at some point of time - check to make sure the tableview delegate and datasource are set to your viewcontroller.
I have made slight modifications in your project.
1. make the UINavigationController the InitialViewController
2. make the FoodMenuController the root of UINavigationController
Now modify your FoodMenuController
#IBOutlet weak var bakeryButton: UIButton!
#IBOutlet weak var breakfastButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBarHidden = true //hide navigationBar in first ViewController
self.bakeryButton.addTarget(self, action: "bakeryButtonAction:", forControlEvents: .TouchUpInside)
self.breakfastButton.addTarget(self, action: "breakfastButtonAction:", forControlEvents: .TouchUpInside)
}
func bakeryButtonAction(sender: UIButton) {
performSegueWithIdentifier("showLunch", sender: self)
}
func breakfastButtonAction(sender: UIButton) {
performSegueWithIdentifier("showBreakfast", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let foodTableViewController: FoodTableViewController = segue.destinationViewController as! FoodTableViewController
if segue.identifier == "showBreakfast" {
foodTableViewController.contentMode = 1
} else if segue.identifier == "showLunch" {
foodTableViewController.contentMode = 2
}
}
Also you can make UINavigationBar visible in FoodTableViewController
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBarHidden = false
}
PS: It is always better not to add segue directly to a UIButton. Alternatively you can add it from the yellow button on top of your FoodMenuController and specify the segue to be fired in UIButtonAction using performSegueWithIdentifier
I can no where see you setting the datasource and delegate of the tableView, please cross check these are both setup.

Updating labels on secondViewController with data from tableViewController

I have a tableView as initial controller and few labels in secondViewController.
When I create a cell with data I want, the idea is to display that data in the secondViewController labels. All works fine, BUT, the labels in the secondVC update only when I hit the back button, to go back to the table view and select the row again.
How can I update the data displayed in the secondVC on the first tap in the tableview cell?
enter code here
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var titles = [String]()
var subjects = [String]()
var previews = [String]()
var textFieldsText = [UITextField!]()
var selectedTitle: String!
var selectedSubject: String!
var selectedPreview: String!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addTitle")
}
override func viewDidAppear(animated: Bool) {
tableView.reloadData()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = titles[indexPath.row]
cell.detailTextLabel?.text = subjects[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedTitle = self.titles[indexPath.row]
selectedSubject = self.subjects[indexPath.row]
selectedPreview = self.previews[indexPath.row]
tableView.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showPreview" {
let dataToPass = segue.destinationViewController as! previewViewController
dataToPass.titlesString = selectedTitle
dataToPass.subjectsString = selectedSubject
dataToPass.previewsString = selectedPreview
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addTitle() {
let addAlert = UIAlertController(title: "New Title", message: "Add new title, subject and a short preview", preferredStyle: .Alert)
addAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
addAlert.addTextFieldWithConfigurationHandler {[unowned self] textField in
textField.placeholder = "Add Title"
textField.textAlignment = .Center
self.textFieldsText.append(textField)
}
addAlert.addTextFieldWithConfigurationHandler { textField in
textField.placeholder = "Add Subject"
textField.textAlignment = .Center
self.textFieldsText.append(textField)
}
addAlert.addTextFieldWithConfigurationHandler { textField in
textField.placeholder = "Add Short Preview"
textField.textAlignment = .Center
self.textFieldsText.append(textField)
}
addAlert.addAction(UIAlertAction(title: "Done", style: .Default){ _ in
self.titles.append(self.textFieldsText[0].text!)
self.subjects.append(self.textFieldsText[1].text!)
self.previews.append(self.textFieldsText[2].text!)
self.tableView.reloadData()
self.textFieldsText.removeAll()
})
presentViewController(addAlert, animated: true, completion: nil)
}
}
class previewViewController: UIViewController {
#IBAction func readButton(sender: UIButton) {
}
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var subjectLabel: UILabel!
#IBOutlet weak var shortPreviewLabel: UITextView!
var titlesString: String!
var subjectsString: String!
var previewsString: String!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: "saveChanges")
titleLabel.text = titlesString
subjectLabel.text = subjectsString
shortPreviewLabel.text = previewsString
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
let dataToDetail = segue.destinationViewController as! detailViewController
dataToDetail.textViewString = self.previewsString
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
If I understand your question right, this may help:
use this didSelectRowAtIndexPath:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("showPreview", sender: indexPath.row)
}
use this prepareForSegue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showPreview" {
let destinationViewController = segue.destinationViewController as! previewViewController
if let index = sender as? Int {
destinationViewController.titlesString = self.titles[index]
destinationViewController.subjectsString = self.subjects[index]
destinationViewController.previewsString = self.previews[index]
}
}
}
And you need to have a segue from ViewController to previewViewController called "showPreview". Like this:

Resources