swift


segue to detailed tableview controller


I am passing data from one view controller to another. The first view controller has a collectionviewcell, and the controller I am segueing to has a tableviewcell. When I click on the cell of the collection view which is also clicking on a user, I want to segue into a detailed view controller that has a list of all the post the user made (which is stored in firebase)
Here is what I have so far: -This is my controller with the collectionviewcell
class WelcomeViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{
var posts = NSMutableArray()
var databaseRef = FIRDatabase.database().reference()
var loggedInUser = FIRAuth.auth()?.currentUser
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
func loadData(){
if (FIRAuth.auth()?.currentUser) != nil{
FIRDatabase.database().reference().child("books").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in
let loggedInUserData = snapshot
if let postsDictionary = snapshot .value as? [String: AnyObject] {
for post in postsDictionary {
self.posts.add(post.value)
}
self.CollectionView.reloadData()
}})}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "details" {
if segue.identifier == "UsersProfile" {
if let indexPath = sender as? IndexPath{
let vc = segue.destination as! UsersProfileViewController
let post = self.posts[indexPath.row] as! [String: AnyObject]
let posted = self.posts[indexPath.row] as! [NSMutableArray: AnyObject]
let username = post["username"] as? String
let userpicuid = post["uid"] as? String
let userpostuid = post["uid"] as? NSMutableArray
vc.username = username
vc.userpicuid = userpicuid
vc.posts = posts
print(indexPath.row)
}
}}
Right now when I click on the cells I segue into the detailed view controller and it displays all the posts made by all the users in my database and I know it is because in my segue I write vc.posts = posts. I am new to swift and I don't know how I will set it up so that when I click a cell (which is also when I click a user) then a detailed tableviewcontroller shows me all the post, only that user has made
Here is what my database looks like
Again, I am trying to only display the post uploaded by indiviual users
You can setup segue from collectionViewController to tableViewController in your storyboard, then give it an identifier (very important).
In your collectionViewController, override prepareForSegue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let vc = segue.destinationViewController as? YourTableViewControllerClassName {
// assign data you want to pass here
}
}
Then in your collectionView:didSelectItemAt method, call performSegueWithIdentifier("yourID", sender: self)
Hope this helps!
Overview:
A collection view displays a list of posts.
Each cell represents a post.
Each cell has a button with the user image when tapped on it, the app segues into UsersProfileViewController.
UsersProfileViewController contains a property posts which represents the posts made by the user.
Question:
How to set the UsersProfileViewController in such a way that it displays only the posts made by the selected user ?
Approach:
Each cell is dequeued and is reused.
When a button is tapped it needs to know which index path the button corresponds to.
Once the indexPath of the cell containing the button is known then we can determine the user associated with it.
Once the user is known filter the posts based on the selected user.
Steps:
Create a subclass of button with indexPath as a property
Use that custom button in your cell
In cellForItemAtIndexPath set the button indexPath
In cellForItemAtIndexPath set the target for the button
When the button is pressed, determine the corresponding username and store it as selectedUserName (view controller property).
In prepareForSegue filter posts based on the selectedUserName
Sample Code:
class CellButton : UIButton {
var indexPath : IndexPath?
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CustomCollectionViewCell
let post = posts[indexPath.row]
cell.titleLabel.text = post["title"]
cell.button.setTitle(post["username"], for: .normal)
cell.button.addTarget(self, action: #selector(tappedOnUserButton(button:)),
for: .touchUpInside)
cell.button.indexPath = indexPath //In your cell make sure you use CellButton instead of UIButton
return cell
}
#objc private func tappedOnUserButton(button: CellButton) {
guard let indexPath = button.indexPath else {
return
}
print("button pressed - \(indexPath)")
let post = posts[indexPath.row]
selectedUserName = post["username"]
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "UsersProfile" {
//Filter posts based on username
//Assumption: posts contains all the posts.
//Assumption: username is a unique way to identify a user, if not use any other field that would uniquely identifies an user
let postsForUser = posts.filter { $0["username"] == selectedUserName }
print("postForUser = \(postsForUser)")
}
}
Preferred Approach:
Create a struct called User (instead of using a dictionary, which is error prone while coding)
Create a struct called Post, Post would have a property called User to map the user - https://itunes.apple.com/us/book/the-swift-programming-language-swift-3-1/id881256329?mt=11
Please learn Swift, each language has some features that you can take advantage of.
Don't force unwrap variables unless you are 100% sure it would contain a non-nil value
Use native types whenever possible (example use Swift Array instead of NSMutableArray)
Please explain your question clearly so that others don't have to spend time trying hard to understand. (Be precise and clear and isolate the problem, and use markdown for formatting)

Related Links

Swift - Calling a func of a UIViewController from a Custom UITableViewCell
Label automatically hide/show on scrolling in Header View
Random Node Location without Overlap
UITableView within UIViewController crashes when the next cell to add would not be visible
SKLabelNode Not Showing [SpriteKit]
How to convert static properties of a Swift class to a Dictionary?
Generating interface from .swift file
Log in Twitter swift
Swift: Create card-like cells in a PFQueryTableViewController (Parse)
SKNode perform animation before removing
Update UI in UIAlertAction handler
How can I add a little white tick to SSRadioButton
Xcode resize vector shape generated with paintcode
Confused by the example code which adds new instance methods to types
Swift NSData getBytes reversed
Swift UIWebView constraints full screen

Categories

HOME
makefile
paypal
semantic-ui
sass
redis
agile
actionscript
windows-store-apps
xtext
iis-7.5
tizen-wearable-sdk
jpanel
wicket
ssr
lagom
flann
game-physics
typeahead
internet-explorer-8
shippo
excel-2010
fabric
hanami
net-snmp
kong
cell-array
smart-mobile-studio
spring-insight
idl
hawtio
bing-maps-api
bigcartel
pmwiki
npm-publish
inkscape
xamarin.uitest
codesys
parse-android-sdk
poco-libraries
initializer
code-behind
soundjs
common.logging
code-composer
spring-bean
double-buffering
w3-total-cache
webdatagrid
livescribe
ruby-on-rails-2
butterknife
teiid
ingres
lotus
vici
hspec
glkit
cron-task
pagekit
soda
remoteapp
picking
qt-linguist
altbeacon
direct3d12
evo
base32
scrollspy
gmaps4rails
aquafold
httpcontext
map-force
roxygen
operations
argb
dynamics-ax-2009
shiva3d
sametime
icsharpcode
sunspot-rails
electronic-signature
hmacsha1
handheld
document-library

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App