Delegate between controllers doesn't work. Why? - ios

I try to use delegate to send data from textField which is in the Detail2(ViewController) to array which is in the ViewController.
I used here print method and first print show that one element has been added to the array but the second print method which is below the ViewVillAppear() show that array is empty. How? I want to be able to to use delegate to add data to my table.
["sdsd"] First print from the console
[]Second print from the console
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var add: UIBarButtonItem!
#IBOutlet var tv: UITableView!
var array :[String] = []
override func viewDidLoad() {
super.viewDidLoad()
tv.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue" {
let vc: Detail2 = segue.destination as! Detail2
vc.delegate = self
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = array[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
array.remove(at: indexPath.row )
tv.reloadData()
}
}
func alert () {
}
override func viewWillAppear(_ animated: Bool) {
tv.reloadData()
print(array)
}
}
extension ViewController: Data {
func tekst(data: String) {
array.append(data)
print(array)
}
}
and Detail2
protocol Data {
func tekst (data: String)
}
class Detail2: UIViewController {
var delegate: Data? = nil
#IBAction func btn(_ sender: Any) {
let sb = storyboard?.instantiateViewController(withIdentifier: "Main" ) as! ViewController
navigationController?.pushViewController(sb, animated: true)
if delegate != nil {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
}
}
#IBOutlet var btn: UIButton!
#IBOutlet var txtfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
btn.backgroundColor = UIColor.blue
btn.tintColor = UIColor.white
btn.layer.cornerRadius = 25
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Just update your function with:
#IBAction func btn(_ sender: Any) {
if delegate != nil {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
navigationController?.popViewController(animated: true)
}
}
Update:
extension ViewController: Data {
func tekst(data: String) {
array.append(data)
print(array)
self.tv.reloadData()
}
}

You need to add this delegate?.tekst(data: napis!) inside completion handler, because you are using navigationController, there is no option for completion handler,So have to add UINavigationController extension like that:
extension UINavigationController {
public func pushViewController(viewController: UIViewController,
animated: Bool,
completion: (() -> Void)?) {
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
pushViewController(viewController, animated: animated)
CATransaction.commit()
}
}
change this
navigationController?.pushViewController(sb, animated: true){
if delegate != nil {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}

Update your code in Detail2 viewcontroller
#IBAction func btn(_ sender: Any) {
if delegate != nil {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
}
navigationController?.popViewController(animated: true)
}

In the ViewController implement the delegate method
func tekst (data: String) {
array.append(data)
}
// in detail
#IBAction func btn(_ sender: Any) {
if txtfield.text != nil {
let napis = txtfield.text
delegate?.tekst(data: napis!)
}
/// dismiss detail here don't push main again
self.navigationController?.popViewController(animated: true)
}

Related

condition on segue identifier in protocol

I have two view controllers 1st name is ViewController and 2nd Name is ContactVC. I have 3 buttons on 1st viewcontroller when i click on a button open 2nd viewController. In 2nd view controller i open phone contacts when i select any contact that contact name should be set as a button title. I have done with 1st button but from 2nd and 3rd button it does not works. Below is the code of 1st ViewController
import UIKit
import ContactsUI
class ViewController: UIViewController,CNContactPickerDelegate {
#IBOutlet weak var con1: UIButton!
#IBOutlet weak var con2: UIButton!
#IBOutlet weak var con3: UIButton!
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.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Contact1Segue"
{
(segue.destination as! ContactVC).delegate = self
}
else if segue.identifier == "Contact2Segue"
{
(segue.destination as! ContactVC).delegate = self
}
else if segue.identifier == "Contact3Segue"
{
(segue.destination as! ContactVC).delegate = self
}
}
func findContacts() -> [CNContact]
{
let store = CNContactStore()
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactImageDataKey,
CNContactPhoneNumbersKey] as [Any]
let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch as! [CNKeyDescriptor])
var contacts = [CNContact]()
do {
try store.enumerateContacts(with: fetchRequest, usingBlock: { ( contact, stop) -> Void in
contacts.append(contact)
})
}
catch let error as NSError {
print(error.localizedDescription)
}
return contacts
}
func contactPickerDidCancel(picker: CNContactPickerViewController)
{
print("Cancel Contact Picker")
}
}
extension ViewController: ContactVCDelegate
{
func updateData(data: String)
{
self.con1.setTitle(data, for: .normal)
self.con2.setTitle(data, for: .normal)
self.con3.setTitle(data, for: .normal)
}
}
Below is the 2nd ViewController Code
import UIKit
import ContactsUI
class ContactVC: UIViewController, CNContactPickerDelegate, UITableViewDataSource, UITableViewDelegate {
var contacts = [CNContact]()
var Name:String?
var delegate: ContactVCDelegate?
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
DispatchQueue.global(qos: .background).async
{
let a = ViewController()
self.contacts = a.findContacts()
OperationQueue.main.addOperation
{
self.tableView!.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
print("Count:\(self.contacts.count)")
return self.contacts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0
{
let cell = tableView.dequeueReusableCell(withIdentifier: "SearchRID", for: indexPath)
return cell
}
else
{
let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID", for: indexPath)
let contact = contacts[indexPath.row] as CNContact
cell.textLabel!.text = "\(contact.givenName) \(contact.familyName)"
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("section:\(indexPath.section), row:\(indexPath.row)")
let allcontact = self.contacts[indexPath.row] as CNContact
Name = allcontact.givenName + allcontact.familyName
self.delegate?.updateData(data: Name!)
print("Name:\(Name)")
_ = self.navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
}
//MARK:- CNContactPickerDelegate Method
func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
contacts.forEach({contact in
for number in contact.phoneNumbers
{
let phonenum = number.value as CNPhoneNumber
print("NUmber is = \(phonenum)")
}
})
}
}
protocol ContactVCDelegate
{
func updateData(data: String)
}
Update your protocol:
protocol ContactVCDelegate
{
func updateData(buttonId:int, data: String)
}
Have a field in your second view controller with buttonId.
And set this value while preparing segue:
(segue.destination as! ContactVC).buttonId = 1
Your Update function:
func updateData(buttonId:int, data: String)
{
switch(buttonId){
case 1:
self.con1.setTitle(data, for: .normal)
break
case 2:
self.con2.setTitle(data, for: .normal)
break
case 3:
self.con3.setTitle(data, for: .normal)
break
}
}
In second view controller, onDidSelect:
self.delegate?.updateData(buttonId:buttonId,data: Name!)

Swift prepareForSegue object is nil

I'm trying to pass the event Object into DetailViewController, but it crashes and says: "fatal error: unexpectedly found nil while unwrapping an Optional value". I'm positive the error is in my prepare(for segue:) function, but I've been at this for hours and I can't find out how to fix it. Any help would be appreciated. Thanks!
Here is my code:
class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var textView: UITextView!
#IBOutlet weak var tableView: UITableView!
var events = [Event]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
parseCSV()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func logOutAction(sender: AnyObject) {
if FIRAuth.auth()?.currentUser != nil {
do {
try FIRAuth.auth()?.signOut()
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SignUp")
present(vc, animated: true, completion: nil)
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
func parseCSV() {
let path = Bundle.main.path(forResource: "eventData", ofType: "csv")
do {
let csv = try CSV(contentsOfURL: path!)
let rows = csv.rows
for row in rows {
let eventTitle = row["Title "]!
let eventLoc = row[" Location "]!
let eventStart = row[" Start_Time "]!
let eventEnd = row [" End_Time"]!
let event = Event(title: eventTitle, loc: eventLoc, start: eventStart, end: eventEnd)
events.append(event)
}
} catch let err as NSError {
print(err.debugDescription)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "eventCell", for: indexPath) as? EventCell{
let event = events[indexPath.row]
cell.updateUI(event: event)
return cell
} else {
return UITableViewCell()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let event = events[indexPath.row]
performSegue(withIdentifier: "detailSegue", sender: event)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detailSeque" {
if let detailVC = segue.destination as? DetailViewController {
if let event = sender as? Event {
detailVC.event = event
}
}
}
}
}
My DetailViewController class:
class DetailViewController: UIViewController {
var event: Event!
#IBOutlet weak var eventTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
eventTitle.text = event.title // error here. says event is nil.
}
}
Since the segue is connected from your cell, it already performed automatically when you tap the cell. Performing it programmatically is resulting in your segue being performed twice: once with the value passed correctly and once without.
You can either change your segue to be connected from the view controller instead of the cell in which case your current code would work, or update your code to do all of the logic in prepareForSegue and remove your implementation of didSelectRowAt:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detailSeque" {
if let detailVC = segue.destination as? DetailViewController {
let row = tableView.indexPathForSelectedRow!.row
detailVC.event = events[row]
}
}
}

SearchController issue, when search the displayController shows a spacing from the Searchbar

The issue is this:
In the storyboard, I must uncheck the Adjust Scroll View Insets, because if not do this, I will get a other issue(https://stackoverflow.com/questions/40974647/uisearchcontroller-issue-nslayoutattribute-do-not-work-in-real-device), and I don't know this if is affect the issue here.(I test in simulator, if check Adjust Scroll View Insets, the issue here will not appear )
My code
import UIKit
import SVProgressHUD
class ChooseStoreViewController: UIViewController,UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {
#IBOutlet weak var tableView: UITableView!
var ori_dataSource: [StoreListModel] = [StoreListModel]()
var dataSource = [String]()
var filterdDataSource = [String]()
var resultSearchController = UISearchController()
var choosedStore:StoreListModel? = nil
var userInfoFromChooseTerant:[String:Any]?
#IBOutlet weak var top_constraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
initData()
initUI()
}
// MARK: - view life
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.isNavigationBarHidden = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.isNavigationBarHidden = true
}
func initData() {
self.resultSearchController = UISearchController(searchResultsController: nil)
self.resultSearchController.searchResultsUpdater = self
self.resultSearchController.dimsBackgroundDuringPresentation = false
self.resultSearchController.searchBar.sizeToFit()
self.resultSearchController.searchBar.placeholder = "search"
self.resultSearchController.searchBar.tintColor = UIColor.black
self.resultSearchController.searchBar.delegate = self
self.tableView.tableHeaderView = self.resultSearchController.searchBar
let nib = UINib(nibName: "TerantListCell", bundle: nil)
// Required if our subclasses are to use: dequeueReusableCellWithIdentifier:forIndexPath:
//tableView.register(nib, forCellReuseIdentifier: "TerantListCell")
self.tableView.register(nib, forCellReuseIdentifier: "TerantListCell")
self.tableView.tableFooterView = UIView.init()
self.tableView.reloadData()
networkForStoreList()
}
func initUI() {
let backNavItem:UIBarButtonItem = UtilSwift.addBackButtonItem(nil, controlelr: self)
backNavItem.action = #selector(navBack)
// print(userInfoFromChooseTerant!)
tableView.separatorStyle = UITableViewCellSeparatorStyle.none
}
// 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.destinationViewController.
// Pass the selected object to the new view controller.
let chooseRole: ChooseRoleViewController = segue.destination as! ChooseRoleViewController
chooseRole.userInfoFromChooseStore = self.userInfoFromChooseTerant
}
// MARK: - search delegate
func searchBarCancelButtonClicked() {
for item:NSLayoutConstraint in self.tableView.constraints {
self.view.setNeedsLayout()
if item.firstAttribute == NSLayoutAttribute.top {
item.constant = 0
}
}
}
// MARK: - searchbar delegate
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setValue("cancel", forKey:"_cancelButtonText")
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
}
// MARK: - private methods
func navBack() {
_ = self.navigationController?.popViewController(animated: true)
}
// MARK: - actions
#IBAction func unwindToChooseStoreVCFromChooseRole(segue: UIStoryboardSegue){
}
#IBAction func nextStepAction(_ sender: UIButton) {
/*if choosedStore == nil {
let lml_alert: LMLDropdownAlertView = LMLDropdownAlertView.init(frame: self.view.bounds)
lml_alert.showAlert(title: Global.hint, detail_Title: "select", cancleButtonTitle: "cacnel", confirmButtonTitle: "confirm", action: { (button) in
})
return
}*/
self.resultSearchController.isActive = false
if self.choosedStore != nil {
_ = self.userInfoFromChooseTerant?.updateValue(self.choosedStore!.userId, forKey: "store_id")
}
self.performSegue(withIdentifier: "ChooseStoreVCToChooseRoleVC", sender: self)
}
// MARK: - network
func networkForStoreList() {
let params:[String:String] = [
"createTime":"-1",
"userId" : self.userInfoFromChooseTerant!["affiliated_id"] as! String
]
// url_terantList
Mysevers.afpost(withHud: true, andAddressname: Global.url_listStore, parmas: params, requestSuccess: { (result) in
let stateCode = UtilSwift.getNetStateCode(result: result as Any, key: Global.net_key_stateCode)
if stateCode == 0 {
let storeArr:[[String : Any]] = UtilSwift.getNetAnyObject(result: result as Any, key: "list") as! [[String : Any]] // Global.net_key_bussines
//self.ori_dataSource = terantArr
for item:[String: Any] in storeArr {
let store_list_model: StoreListModel = StoreListModel.initStoreListModelWithDic(dic: item)
self.ori_dataSource.append(store_list_model)
}
for item:StoreListModel in self.ori_dataSource {
self.dataSource.append(item.name)
}
self.tableView.reloadData()
}else if stateCode == -1 {
SVProgressHUD.showError(withStatus: "err")
}
}, failBlcok: {
SVProgressHUD.showError(withStatus: "err")
})
}
// MARK: - tableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.resultSearchController.isActive {
return filterdDataSource.count
}else {
return dataSource.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: TerantListCell = tableView.dequeueReusableCell(withIdentifier: "TerantListCell", for: indexPath) as! TerantListCell
if self.resultSearchController.isActive {
cell.title_label.text = self.filterdDataSource[indexPath.row]
}else {
cell.title_label?.text = self.dataSource[indexPath.row]
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.choosedStore = self.ori_dataSource[indexPath.row]
}
// MARK: - regexp
func updateSearchResults(for searchController: UISearchController) {
self.filterdDataSource.removeAll(keepingCapacity: false)
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %#", searchController.searchBar.text!)
let array = (self.dataSource as NSArray).filtered(using: searchPredicate)
self.filterdDataSource = array as! [String]
self.tableView.reloadData()
}
}
Go to ".storyboard" file where "ChooseStoreViewController" exist. Then click on UITableView and change tableView constraints as follows:
Check Top Space constraint.

Passing data back to previous view controller after selecting table view cell

I'm having trouble passing data after selecting a table view cell to the previous view controller. I'm pretty much trying to change a label from the previous view controller after selecting a table view cell. Could anyone help me go about this? I'm trying to change the UITextField after selecting a cell.
UIViewController:
class WhoToOdds: UIViewController, sendBack,UITextFieldDelegate{
#IBOutlet var chosenContact: UITextField!
#IBOutlet var oddsTextBox: UITextView!
var friend: String?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
func sendNameToPreviousVC(selectedfriendName: String) {
friend = selectedfriendName
chosenContact.text = friend
}
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.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "friendList"{
let friendViewController = (segue.destinationViewController as! friendListController)
var fbRequest = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil);
fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
println("Friends are : \(result)")
PFUser.currentUser()?["friend_list"] = result
PFUser.currentUser()?.save()
print(result)
var resultdict = result as! NSDictionary
println("Result Dict: \(resultdict)")
friendViewController.friendArray = resultdict.objectForKey("data") as! NSArray
} }
}
}
#IBAction private func submitChallenge(sender: AnyObject) {
navigationController?.popViewControllerAnimated(true)
}
}
TableViewController:
protocol sendBack
{
func sendNameToPreviousVC(contact: String)
}
class friendListController: UITableViewController, UITableViewDataSource, UITableViewDelegate{
var friendArray:NSArray = ["a","b","c"]
var valueDict:NSDictionary = [:]
var mDelegate:sendBack?
var selectedFriend :String?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friendArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("friend", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel!.text = (friendArray[indexPath.row] as! String)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let indexPath = tableView.indexPathForSelectedRow();
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!
selectedFriend = currentCell.textLabel!.text as String!
sendBackFriendList(selectedFriend!)
navigationController?.popViewControllerAnimated(true)
}
func sendBackFriendList(name: String){
self.mDelegate?.sendNameToPreviousVC(name)
}
}
Your delegate needs to be set. In your case you have to set it inside prepareForSegue method like
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "friendList"{
let friendViewController = (segue.destinationViewController as! friendListController)
friendViewController.mDelegate = self //Include this line
//rest of the code
}
}
You didn't set the delegate in your segue, so mDelegate is nil in your sendBackFriendList method

How do I pass the same textview, button, and label after clicking the Cell swift?

I would like to make it so that when the user clicks on the cell, it shows exactly everything in the cell. TextView, Buttons, and label. How can I do this?
Here is the code:
TableCell:
import UIKit
class TableViewCell: UITableViewCell {
#IBOutlet weak var textView: UITextView!
#IBAction func 1Button(sender: AnyObject) {
}
#IBAction func 2Button(sender: AnyObject) {
}
#IBOutlet weak var counter: 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
}
}
TableViewController:
import UIKit
let reuseIdentifier = "Cell"
class UserFeedTableViewController: UITableViewController, ComposeViewControllerDelegate {
private var posts: [PFObject]? {
didSet {
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
Downloader.sharedDownloader.queryForPosts()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "queryFeeds:", name: queryNotification, object: nil)
}
// Notification SEL
func queryFeeds(notification: NSNotification) {
posts = notification.object as? [PFObject]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "postSegue" {
let nav = segue.destinationViewController as! UINavigationController
let composeVc = nav.topViewController as! ComposeViewController
composeVc.delegate = self
}
if segue.identifier == "commentsSegue" {
let vc = segue.destinationViewController as! CommentsViewController
let cell = sender as! UITableViewCell
let indexPath = tableView.indexPathForCell(cell)
let object = posts![indexPath!.row]
vc.postObject = object
}
}
//dismiss compose vc
func dismissComposeViewController(ViewController: ComposeViewController) {
dismissViewControllerAnimated(true, completion: nil)
}
func reloadTableViewAfterPosting() {
dismissViewControllerAnimated(true, completion: nil)
Downloader.sharedDownloader.queryForPosts()
}
}
extension ViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return posts?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UserFeedTableViewCell
// Configure the cell...
if let posts = posts {
let object = posts[indexPath.row]
cell.textView?.text = object["post"] as? String
}
return cell
}

Resources