for the first view i prepare to segue 3 textFields:(Sorry for my bad english as well)
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "salvar") {
var view = segue.destinationViewController as! SecondView
view.end = endereco.text
view.area = area.text
view.data = data.text
}
}
the problem is on secondView the array is repeating (and don't add new data to array, only replace it), making the 3 labels from cell repeating with the same data, heres the secondView code:
class secondView: UITableViewController {
var end = ""
var area = ""
var data = ""
var array: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.array = [end, area, data]
}
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 self.array.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! AgendaCell
cell.label1.text = self.array[indexPath.row] as String
cell.label2.text = self.array[indexPath.row] as String
cell.label3.text = self.array[indexPath.row] as String
return cell
}
how i can really add new data to array, and place each for the ordered label from cell?
Related
I m getting this error :fatal error: Index out of range .I can't get what i m doing wrong .What i'm trying to do is , access an array dictionary by using an integer index than pass a string to get the value mapped to it .The sample works fine on playground but not excode why ? (The array dictionary is not empty)
Here is my code
var CondoIndivi2 = [[String:AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
scrollView.contentSize.height = 1500
print(CondoIndivi2)
if let description_Condo = self.CondoIndivi2[0]["description"] as? String {
print(description_Condo)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is the view that sends data to CondoIndivi2
import UIKit
import Alamofire
import SwiftyJSON
class SignleCondoTableViewController: UITableViewController {
#IBOutlet var tableview: UITableView!
var singleCondoData = [[String:AnyObject]]()
var CondoIndivi = [[String:AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.tableView.delegate = self
self.tableView.dataSource = self
}
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 singleCondoData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SignleTableTableViewCell
if singleCondoData.count != 0 {
let dict = singleCondoData[indexPath.row] as NSDictionary
//cell.label1.text? = (dict["name"] as? String)!
if let nullcheck = (dict["address"] as? String) {
cell.label2.text? = nullcheck
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let dict = singleCondoData[indexPath.row] as NSDictionary
if let unitNullCheck = (dict["mls_number"] as? String) {
let item_id = unitNullCheck
getCondoUnits(item_id)
print(item_id)
}
}
//get the individual condo id
func getCondoUnits(condo_id : String){
Alamofire.request(.GET, "http://android.goidx.com/search/?mls_number=" + String(condo_id)).validate().responseJSON { response in
if let value = response.result.value {
let json = JSON(value)
if let resData = json.arrayObject {
self.CondoIndivi = resData as! [[String:AnyObject]]
print(self.CondoIndivi)
}
if self.CondoIndivi.count > 0 {
self.tableview.reloadData()
}
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case "details" :
let buildingdDetailVC = segue.destinationViewController as! DetailsViewController
buildingdDetailVC.CondoIndivi2 = self.CondoIndivi
default:
break
}
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
As #James put in his comment, you're creating an empty array in your code:
var CondoIndivi2 = [[String:AnyObject]]()
And then you're trying to access indexing in the position 0:
if let description_Condo = self.CondoIndivi2[0]["description"] as? String {
print(description_Condo)
}
And of course, you will have a runtime error of Index of out Range because your array it's empty, you always need to be sure before index an array that the index is greater than zero, less than equal to the size of the array and the array is not empty.
I hope this help you.
Inside your getCondoUnits(condo_id : String) is an asynchronous block(Alamofire.request), the CondoIndivi2 is received later than the viewDidLoad is executed. You should just pass condo_id to next viewController and do the request in it.
import UIKit
import Alamofire
import SwiftyJSON
class RecentAdded: UIViewController ,UITableViewDataSource,UITableViewDelegate{
#IBOutlet var tableView: UITableView!
var list:JSON!
var sendurl:String!
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, "http://api.dirble.com/v2/stations/recent", parameters: ["token": "260674ecb51572a8faa4e77199"])
.responseJSON { response in
if let json = response.result.value {
self.list = JSON(data: response.data!)
print(self.list) /// Showing less element if element is more than 25
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.reloadData()
print(self.list.arrayValue.capacity) // Printing the actual capacity
}
}
// Do any additional setup after loading the view.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.list.arrayValue.capacity
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! RecentCellTableViewCell
let sampleArray = self.list.array
let imageURL:String! = sampleArray![indexPath.row]["image"]["thumb"]["url"].stringValue
if imageURL != ""{
Alamofire.request(.GET, imageURL).responseImage { (response) -> Void in
guard let image = response.result.value else { return }
cell.img!.image = image
}
}else{
cell.img!.image = UIImage(named: "rad")!
}
cell.nm?.text = sampleArray![indexPath.row]["name"].stringValue
let catarr = sampleArray![indexPath.row]["categories"].array
let des:String! = "category : " + catarr![0]["title"].stringValue + " " + "slug : " + catarr![0]["slug"].stringValue
cell.des?.text = des
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! RecentCellTableViewCell
let sampleArray = self.list.array
let url = sampleArray![indexPath.row]["streams"].array
sendurl = url![0]["stream"].stringValue
self.performSegueWithIdentifier("next", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//
if (segue.identifier == "next") {
// initialize new view controller and cast it as your view controller
var viewController = segue.destinationViewController as! Player
viewController.urll = sendurl
}
}
}
My problem is when i am printing list.arrayvalue.capacity it is showing the actual size of array which is correct but when i tried to print element of array it show's less element then its counting. so i am not sure what is wrong in code????/
The main problem is in printing element. Not printing all elements.
I think you're confusing the array capacity with the actual item count. For numberOfRowsInSection, use the count property of the array instead:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.list.arrayValue.count
}
More details about count vs. capacity in this answer: Swift array.capacity vs array.count
ok so I have the user input a name into a textfield and a button passes the name to a tableview in another view, the table view lists the name but when a new name is added it overwrites the previous name instead of listing all names added to the tableview. here is my code:
viewcontroller1:
#IBAction func addPlant(sender: AnyObject) {
let array = self.title
NSUserDefaults.standardUserDefaults().setObject(array, forKey: "userName")
NSUserDefaults.standardUserDefaults().synchronize()
}
viewcontroller2:
#IBOutlet weak var tableView: UITableView!
var userDefaults = NSUserDefaults.standardUserDefaults()
var ourText = String()
var textArray:[String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
//self.tableview.delegate = self
self.tableView.dataSource = self
ourText = userDefaults.stringForKey("userName")!
textArray.append(ourText)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return textArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = textArray[indexPath.row]
return cell
}
You can use
textArray = NSUserDefaults.standardUserDefaults().arrayForKey("userName")
Or
textArray = NSUserDefaults.standardUserDefaults().objectForKey("userName")
I am creating an application that, written a string in a textfield, saves it in an array. The array is showed in a tableViewController embedded in the mainViewController. The situation is the following.
http://i.stack.imgur.com/z5uTc.png.
I want that every time I tap the green "Save" button, the string I wrote in the textField is saved and showed in the tableView and the textField returns empty, so I can re-write a string, that is added in the array. The tableView, in this case, shows the two strings, I wrote in the same textField. I tried to write the code for the two viewControllers (the mainViewVC and the tableVC).
MainVC
import UIKit
class mainVC: UIViewController {
#IBOutlet var txtField: UITextField!
var embTableVC: tableVC!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "embededTableVC" {
embTableVC = segue.destinationViewController as! tableVC
}
}
#IBAction func Save() {
if let Text = txtField.text {
if txtField.text == "" {
myArray.append(Text)
let row = myArray.count-1
let indexPath = NSIndexPath(forRow: row, inSection: 0)
embTableVC.myTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
txtField.text = ""
txtField.resignFirstResponder()
}
}
TableVC
import UIKit
var myArray = [String]()
class tableVC: UITableViewController {
#IBOutlet var myTableView: UITableView! {
didSet {
myTableView.dataSource = self
myTableView.delegate = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
myTableView.dataSource = self
myTableView.delegate = self
myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "customcell")
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
myTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCellWithIdentifier("customcell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = myArray[indexPath.item]
return cell
}
The code I wrote doesn't work. I can compile and run the application on my device, but when I tap the green "Save" button, the app crashes. The error message is "fatal error: unexpectedly found nil while unwrapping an optional value" on the line: embTableVC.myTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) in the "Save" IBAction.
Can you help me?
Thanks a lot:)
You init embTableVC only when you segue to the next ViewController, but you try to access it at your save function, while it is still nil.
init it before you access it.
I am creating an application that, written a string in a textfield, saves it in an array. The array is showed in a tableViewController embedded in the mainViewController. The situation is the following.
http://i.stack.imgur.com/z5uTc.png.
I want that every time I tap the green "Save" button, the string I wrote in the textField is saved and showed in the tableView and the textField returns empty, so I can re-write a string, that is added in the array. The tableView, in this case, shows the two strings, I wrote in the same textField. I tried to write the code for the two viewControllers (the mainViewVC and the tableVC).
MainVC
import UIKit
class mainVC: UIViewController {
#IBOutlet var txtField: UITextField!
var embTableVC: tableVC!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "embededTableVC" {
embTableVC = segue.destinationViewController as! tableVC
}
}
#IBAction func Save() {
if let Text = txtField.text {
if txtField.text == "" {
myArray.append(Text)
let row = myArray.count-1
let indexPath = NSIndexPath(forRow: row, inSection: 0)
embTableVC.myTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
txtField.text = ""
txtField.resignFirstResponder()
}
}
TableVC
import UIKit
var myArray = [String]()
class tableVC: UITableViewController {
#IBOutlet var myTableView: UITableView! {
didSet {
myTableView.dataSource = self
myTableView.delegate = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
myTableView.dataSource = self
myTableView.delegate = self
myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "customcell")
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
myTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCellWithIdentifier("customcell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = myArray[indexPath.item]
return cell
}
The code I wrote doesn't work. I can compile and run the application on my device, but when I tap the green "Save" button, the app crashes. The error message is "fatal error: unexpectedly found nil while unwrapping an optional value" on the line: embTableVC.myTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) in the "Save" IBAction.
Can you help me?
Thanks a lot:)