if statement for buttons in swift - ios

I am coding a program which its home has 6 buttons
if you press a button, it shows a TableView when a row is pressed, it shows new viewconroller which show Row Data Details
the TableView takes its data from JSON URL and this JSON URL has all data on it (6 section).
button(X) to show Section(X)Data
[X=1; X=<6]
i coded it with a long way: every button(X) leads to [Button(X)ViewContoller] and every has [Button(X)TableViewCell]
[X=1; X=<6]
so i have 6 ViewContoller and 6 TableViewCell file.
i think about make an If statement for the 6 buttons instead of separated 2 file for every button, so that what i mean:
if button(X) is pressed,it will show Section(X)Data in the TableView
[[X=1; X=<6]]
i tried to do it a lot, but no way
can any one help me on If statement coding?

You just have to:
Set different tags for the buttons
"Plug" all the buttons in the same method
Check which button was clicked and change set your model accordingly
Tip: You can access properties of your destination view controller using the segue.destinationViewController property inside the prepareForSegue(segue: sender:) method.
EDIT: For example:
Create var buttonTag : Int?
Create a method like #IBAction func clicked(sender: UIButton) {
self.buttonTag = sender.tag
}
Pass it on the way you think is betteroverride func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
segue.destinationViewController?.buttonTag = self.buttonTag
}
Do whatever you have to do with data in your destination view controller

Related

Reload same View Controller but with different information

I have a Detail View Controller and I want to show the same Detail View Controller but with a different item.
var nexttype : Type!
let nexttypeVC = TypeDetailVC()
#IBAction func buttonTapped(_ sender: UITapGestureRecognizer) {
nexttype = type.Array![0]
nexttypeVC.type = next.type
self.navigationController?.pushViewController(nexttypeVC, animated: true)
}
When I print the name or a identifier of the item I get the correct one, but when I launch the simulator I get error. The values of the labels and everything is nil.
How can I tell the view controller to reload again but with a different item?
Call performSegue(withIdentifier:) rather than pushViewController. You'll need to programmatically register a segue or add one via storyboard. Then use prepare(for segue: sender:) to give the destination ViewController the item you wish. Note that the destination's viewDidLoad() is called after the prepareForSegue.
This is the standard Apple-recommended way to seed the destination ViewController with data it needs prior to its load.
Instead of pushing the same view controller onto the navigation stack. Try to arrange all the logic to update UI elements into a method. Call this method in viewDidLoad(). Calling self.viewDidLoad() is not a good idea.
Use observer pattern and call the method that updates UI elements.

Unable to call embedded segue the second time

I'm trying to build an app similar to Instagram, and I'm stuck at the comments portion. On the left side of the image, it is a VC that has an embedded container view with UITextField and UIButton at the bottom. The container view is embedded with a UITableView that contains all the user profile image, username and the comment itself.
At first load, it can perfectly grab all comments for that post from server side, and displayed perfectly. However, I am unable to call the segue again using prepareForSegue to update the UITableView. I'm receiving an error:
There are unexpected subviews in the container view. Perhaps the embed
segue has already fired once or a subview was added programmatically?
Below are my codes:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "getCommentSegue"){
if let destination = segue.destinationViewController as? CommentsTVC{
if(!self.commentID.isEmpty){
destination.UpdateCommentRow(self.profileImage, commentID: self.commentID, comment: self.postComment, dateTimePost: self.dateTime)
self.commentID = String()
}
destination.postID = self.postID
}
}
}
And after successfully adding a row to my database in the dispatch_async:
self.performSegueWithIdentifier("getCommentSegue", sender: nil)
I've also noticed that when it append new comment to my existing object that stores all the comments, the count for it is 0. I believe it is taking a new reference for the object. Please help!
embed navigationcontroller to container view and then try. It may solve youar problem i think..!!
Remove your container view's subviews before you call performSegue.

How to keep user inputs within corresponding text fields after segue [Swift]

I have two view controllers, first view containing "user form" for inputs and second to display the final results. Everything seems to be working fine, i.e. I can send the final results using "prepareForSegue" function (see below)
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var SecondVC: SecondViewController = segue.destinationViewController as! SecondViewController
SecondVC.receivedDP_Summary = summaryDP
SecondVC.receivedDC_Summary = summaryDC
SecondVC.receivedDP_CA_Summary = summaryDrillPipe_CsgAnnulus
SecondVC.receivedDC_CA_Summary = summaryDrillCollar_CsgAnnulus
}
However, as soon as I return to first control view after initialising segue, all the user inputs disappear. Is there any way to store the user inputs within the respective text field so they can be manipulated to see varying results?
I am still very new to programming, so I will really appreciate any help

Show a loading animation with swift while waiting for the data from Parse

I've browsed through many q&a-s here but almost all of them are way too specific for the use cases of other people.
My situation is more general and sort of simple:
iOS\Swift
I have a button which when clicked - moves the user to the next view.
At the same time as the button is clicked it also executes a query to Parse to fetch the data which will be displayed on the next view.
I'm using Parse's async query.getObjectInBackgroundWithId("jjjkkkdddd")
So if my code runs as is = click -> move to the next view -> empty
because fetching stuff takes a second or so.
What i want is to have a small animation popping up when user clicks a button to tell them that the data is being fetched at the moment and move to the next view once data arrives.
Here is my button tap code:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "1") {
var svc = segue.destinationViewController as ViewControllerQuotes;
svc.toPass = functionToFetchDataFromParse() //<- takes longer than
//switching to the next view
//toPass is a var which lands into the next view
//and it's value is displayed to the user.
}
}
I am quite fresh with Swift and iOS dev so I can't figure this one out still:(
On the button tap just use addSubview() to add a UI element like UIActivityIndicatorView.
In the callback from Parse, remove the view and go to the next controller, calling the segue programatically.
SOLUTION FOR ME:
Ok i fiddled around and found the best way which suites me for now. what I do is from View1 the button is pressed and it tell the view controller of the 2-nd view to fire up the data fetching function.
In the 2-nd vie controller once it trigger the async function for retrieving data from Parse it also shows the activity indicator and make it run.
The user sees an empty screen with an activity spinner running. once the async function gets back the data it pushes it into a an empty label and shutsdown+hides the activity indicator.
Works great for my case. no interface hanging. and clear for the user about what's happening where and when.
Thanks to everyone!
p.s. this works for me because that's the end of the lifecycle for the retrieved data. if there were other functions depending on it - this wouldn't work:(
What about setting the object on the segue's destination View controller and then fetch the object, and then reload the view?
This would be:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "1") {
var svc = segue.destinationViewController as ViewControllerQuotes;
svc.yourObjectWhichIsToFetch = yourObjectWhichYouWantToPass //need to create a variable on the ViewControllerQuotes!
}
}
And then in the ViewControllerQuotes class:
class ViewControllerQuotes:ViewController {
var yourObjectWhichIsToFetch:PFObject?
override func viewDidLoad(){
super.viewDidLoad()
yourObjectWhichIsToFetch.fetchInBackgroundWithBlock({
(object, error) -> Void in
if error == nil {
//update the UI
}
})
}
}
With this code, you don't need to show any loading note (what is really ugly).

Swift - Performing Segue from UITableViewCells to different View Controller Destinations

so I am having issues figuring out how to implement code for the following purpose:
Essentially my app allows a user on the opening screen to type different categories in a UItextfield, hit enter, and then have those categories appear in a UITableView (all on the same initial view controller). For example the user could enter "Friends from home", "College Friends", "NBA Players".
From there, I want the user to be able to drill down on one of the rows, and be taken by a segue to a UITableView controller where they can add names to those lists and ultimately be able to rank them for fun...
But my question currently is once the user has added the groups that he wants on the initial view controller, how does he/she drill down and segue to a SPECIFIC view controller based on the row he/she tapped?
(I want to post a picture of my storyboard but I don't have the necessary 10 reputation points yet!)
I tried code like this but have gotten no results. I will also note that I dragged a show segue from the uitableviewcell on the opening view controller to the UITableViewController (segue is named "EachGroup").
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "EachGroup") {
// pass data to next view
let UIViewController:ViewController = segue.destinationViewController as ViewController
let indexPath = self.tableView.indexPathForSelectedRow()
}
That's not a new question, many topics about.
You should specify a tag on each cell : cell.tag = 0
In your prepareForSegue, use :
if sender!.tag.littleEndian == 0
{
let UIViewController:ViewController = segue.destinationViewController as YourSpecificViewcontroller
}
else if sender!.tag.littleEndian == 1
{
let UIViewController:ViewController = segue.destinationViewController as YourOtherSpecificViewcontroller
}
Hope it helps,
Sidd.

Resources