I'm trying to implement a refresh button in navigationBar, so when the button is clicked I need to reload the tableView, I have this code, but its not working, for sure the func is called because I put a println inside, Im also declare the reload on ViewDidAppear, but nothing happens :
import UIKit
class CommentsTableViewController: PFQueryTableViewController {
#IBOutlet var tabletView: UITableView!
var object : PFObject?
// Initialise the PFQueryTable tableview
override init(style: UITableViewStyle, className: String!) {
super.init(style: style, className: className)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// Define the query that will provide the data for the table view
override func queryForTable() -> PFQuery {
var query = PFQuery(className: "gameScore")
query.orderByDescending("createdAt")
query.whereKey("ObjectId", equalTo: "XDP1rc8Rmq")
return query
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
// Refresh the table to ensure any data changes are displayed
self.tabletView.reloadData()
println("Reloading")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
var cell = tableView.dequeueReusableCellWithIdentifier("CommentCellIdentifier") as! CommentsCell!
if cell == nil {
cell = CommentsCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CommentCellIdentifier")
}
if let object = object?["user"] as? String {
cell?.username?.text = object
}
return cell
}
func buttonIconAction(sender:UIButton!)
{
println("Reloading")
self.tableView.reloadData()
}
}
Any suggestions?
Thanks.
Instead of calling tableView.reloadData(), it looks like PFQueryTableViewController has a method called loadObjects(). Try calling that instead.
Related
Hello I'm in trouble with making UITableview. I made cell as nib file and want to display the cell in the UITableView. But nib file doesn't show in the UItableview when I start the app. I don't know how to figure this out. the source is below
import UIKit
class DownLoadPlayViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
#IBOutlet var tableview: UITableView!
#IBOutlet var totalNumSizeInfo:UILabel!
let cellID:String = "DownLoadPlayViewControllerCell"
var downloadedContents: [Dictionary<String,String>] = []
var showContents: Dictionary<String,String> = [:]
override func viewDidLoad() {
super.viewDidLoad()
self.tableview.delegate = self
self.tableview.dataSource = self
self.tableview.registerClass(DownLoadPlayViewControllerCell.classForCoder(), forCellReuseIdentifier: "DownLoadPlayViewControllerCell")
// self.tableview.registerClass(DownLoadPlayViewControllerCell.self, forCellReuseIdentifier: "DownLoadPlayViewControllerCell")
// self.tableview.registerNib(UINib(nibName: "DownLoadPlayViewControllerCell", bundle: nil), forCellReuseIdentifier: "DownLoadPlayViewControllerCell")
downloadedContents = getDownloadInformation()!;
totalNumSizeInfo.text = "초기화 상태"
// let contentInfo : Dictionary<String,String> = self.downloadedContents[0]
// print(contentInfo["contentTitle"])
// print(contentInfo["viewDate"])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*Podlist에 있는 다운로드 파일정보를 가져온다. */
func getDownloadInformation() -> [Dictionary<String,String>]?{
var returnValue : [Dictionary<String,String>]? =
NSUserDefaults.standardUserDefaults().objectForKey("downloadedContents") as? [Dictionary<String,String>]
if((returnValue?.isEmpty) == true){
returnValue = nil
}
return returnValue
}
// func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// return 1
// }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return downloadedContents.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
// let cell = tableView.dequeueReusableCellWithIdentifier("DownLoadPlayViewControllerCell", forIndexPath: indexPath) as! DownLoadPlayViewControllerCell
let cell = tableView.dequeueReusableCellWithIdentifier("DownLoadPlayViewControllerCell") as! DownLoadPlayViewControllerCell
let contentInfo : Dictionary<String,String> = self.downloadedContents[indexPath.row]
cell.titleLabel?.text = contentInfo["contentTitle"]
cell.dateLabel?.text = contentInfo["viewDate"]
return cell;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let contentInfo : Dictionary<String,String> = self.downloadedContents[indexPath.row]
print(contentInfo["downLoadURL"])
}
//MARK: ButtonClickArea
#IBAction func closeButtonClick(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
You need reloadData for your tableview after run the command downloadedContents = getDownloadInformation()!. Just run tableview.reloadData() like that:
downloadedContents = getDownloadInformation()!;
tableview.reloadData() //---------> add new like here
totalNumSizeInfo.text = "초기화 상태"
Here is how to use a custom created cell.
Note: I am not using StoryBoard and I have created the cell in a nib.
CustoMCell Class Code:
import UIKit
class ActivityTableViewCell: UITableViewCell {
// MARK: - Constants & variable
// your outlets if any
// MARK: - UITableViewCell methods
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
}
// MARK: - helper methods
class func cellForTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath) -> ActivityTableViewCell {
let kActivityTableViewCellIdentifier = "kActivityTableViewCellIdentifier"
tableView.registerNib(UINib(nibName: "ActivityTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: kActivityTableViewCellIdentifier)
let cell = tableView.dequeueReusableCellWithIdentifier(kActivityTableViewCellIdentifier, forIndexPath: indexPath) as! ActivityTableViewCell
return cell
}
}
And this is how I use it in my TableView
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = ActivityTableViewCell.cellForTableView(tableView, atIndexPath: indexPath)
// access your cell properties here
return cell
}
I solve the problem by modifying the tablecellController like this
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.alpha = 0
UIView.animateWithDuration(0.2, delay: 0, options: .CurveEaseIn, animations: {
self.alpha = 1
}, completion: { finished in
})
}
I have created a basic layout for searchViewcontroller in which I enter a data that I want to search inside parse table as a query and search is completed and the cell appears. I have tried searching but various errors are appearing. I have no clue to do this.
I'm trying to create an independent ViewController for search.
class SearchViewController: PFQueryTableViewController, UISearchBarDelegate {
// Table search bar
#IBOutlet weak var searchBar: UISearchBar!
// Initialise the PFQueryTable tableview
override init(style: UITableViewStyle, className: String!) {
super.init(style: style, className: className)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
// Configure the PFQueryTableView
self.parseClassName = "Countries"
self.textKey = "nameEnglish"
self.pullToRefreshEnabled = true
self.paginationEnabled = false
}
//override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as! CustomTableViewCell!
if cell == nil {
cell = CustomTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CustomCell")
}
// Extract values from the PFObject to display in the table cell
if let nameEnglish = object?["nameEnglish"] as? String {
cell.customNameEnglish.text = nameEnglish
}
if let capital = object?["capital"] as? String {
cell.customCapital.text = capital
}
// Display flag image
var initialThumbnail = UIImage(named: "question")
cell.customFlag.image = initialThumbnail
if let thumbnail = object?["flag"] as? PFFile {
cell.customFlag.file = thumbnail
cell.customFlag.loadInBackground()
}
return cell
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
var detailScene = segue.destinationViewController as! DetailViewController
// Pass the selected object to the destination view controller.
if let indexPath = self.tableView.indexPathForSelectedRow! {
let row = Int(indexPath.row)
detailScene.currentObject = objects?[row] as? PFObject
}
}
// Define the query that will provide the data for the table view
override func queryForTable() -> PFQuery {
// Start the query object
let query = PFQuery(className: "Countries")
// Add a where clause if there is a search criteria
if searchBar.text != "" {
query.whereKey("searchText", containsString: searchBar.text!.lowercaseString)
}
// Order the results
query.orderByAscending("nameEnglish")
// Return the qwuery object
return query
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Force reload of table data
self.loadObjects()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Force reload of table data
self.loadObjects()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// Clear any search criteria
searchBar.text = ""
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Force reload of table data
self.loadObjects()
}
override func viewDidAppear(animated: Bool) {
// Refresh the table to ensure any data changes are displayed
tableView.reloadData()
// Delegate the search bar to this table view class
searchBar.delegate = self
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
let objectToDelete = objects?[indexPath.row] as! PFObject
objectToDelete.deleteInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
// Force a reload of the table - fetching fresh data from Parse platform
self.loadObjects()
} else {
// There was a problem, check error.description
}
}
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
}
If any clue is provided I'll be grateful.
This code is in reference with Bizzi-Body Parse Tutorial .
When I wireframe it, the cell is nested above the TableView. My project structure is that I have a main view controller and a subclass of a TableView that's also using a TableViewCell that I subclassed. Everything is in place, I have no idea why it's not showing.
import UIKit
class ViewController: UIViewController{
#IBOutlet weak var tv: TaskTableView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
My subclass of UITableView.
import UIKit
class TaskTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
var title: String = ""
var detail: String = ""
var time: NSDate = NSDate()
var data = ["asdf","asdf","sadf"]
init(frame: CGRect, title: String, detail: String, time: NSDate)
{
self.title = title
self.detail = detail
self.time = time
super.init(frame: frame, style: UITableViewStyle.Plain)
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return data.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
tableView.registerNib(UINib(nibName: "NewTVCell", bundle: nil), forCellReuseIdentifier: "toDoCell")
let cell = tableView.dequeueReusableCellWithIdentifier("toDoCell", forIndexPath: indexPath) as! NewTVCell
cell.title.text = data[indexPath.row]
return cell
}
I have a parse class of country names, and have a swift tableview controller that pulls the list of countries from Parse and allows you to search for country name. For example:
Canada
China
Iraq
etc
If I search for "Canada" nothing comes up, but if I search "anada" I get results. For some reason it is ignoring the first character, any idea why this is happening?
import UIKit
class TableViewController: PFQueryTableViewController, UISearchBarDelegate {
// Sign the user out
#IBAction func signOut(sender: AnyObject) {
PFUser.logOut()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("SignUpInViewController") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
}
#IBAction func add(sender: AnyObject) {
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("TableViewToDetailView", sender: self)
}
}
// Table search bar
#IBOutlet weak var searchBar: UISearchBar!
// Initialise the PFQueryTable tableview
override init(style: UITableViewStyle, className: String!) {
super.init(style: style, className: className)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Configure the PFQueryTableView
self.parseClassName = "Countries"
self.textKey = "nameEnglish"
self.pullToRefreshEnabled = true
self.paginationEnabled = false
}
//override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as! CustomTableViewCell!
if cell == nil {
cell = CustomTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CustomCell")
}
// Extract values from the PFObject to display in the table cell
if let nameEnglish = object?["nameEnglish"] as? String {
cell.customNameEnglish.text = nameEnglish
}
if let capital = object?["capital"] as? String {
cell.customCapital.text = capital
}
// Display flag image
var initialThumbnail = UIImage(named: "question")
cell.customFlag.image = initialThumbnail
if let thumbnail = object?["flag"] as? PFFile {
cell.customFlag.file = thumbnail
cell.customFlag.loadInBackground()
}
return cell
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
var detailScene = segue.destinationViewController as! DetailViewController
// Pass the selected object to the destination view controller.
if let indexPath = self.tableView.indexPathForSelectedRow() {
let row = Int(indexPath.row)
detailScene.currentObject = objects?[row] as? PFObject
}
}
// Define the query that will provide the data for the table view
override func queryForTable() -> PFQuery {
// Start the query object
var query = PFQuery(className: "Countries")
// Add a where clause if there is a search criteria
if searchBar.text != "" {
query.whereKey("nameEnglish", containsString: searchBar.text.lowercaseString)
}
// Order the results
query.orderByAscending("nameEnglish")
// Return the qwuery object
return query
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Force reload of table data
self.loadObjects()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Force reload of table data
self.loadObjects()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// Clear any search criteria
searchBar.text = ""
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Force reload of table data
self.loadObjects()
}
override func viewDidAppear(animated: Bool) {
// Refresh the table to ensure any data changes are displayed
tableView.reloadData()
// Delegate the search bar to this table view class
searchBar.delegate = self
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
let objectToDelete = objects?[indexPath.row] as! PFObject
objectToDelete.deleteInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
// Force a reload of the table - fetching fresh data from Parse platform
self.loadObjects()
} else {
// There was a problem, check error.description
}
}
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
}
Just realized the query.wherekey function is not case sensitive, fixed the problem
So I have a problem where I get shown the error
multiple inheritance from classes UIViewController and UIFont
and being new to programming, I don't really understand what is wrong. So what does this error mean? Can't I add more protocols to the class? This is how my code looks
import UIKit
import Foundation
var items:[String] = []
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIFont {
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.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
cell.textLabel?.text = items[indexPath.row]
return cell
}
func fontWithSize(fontSize: 130) -> UIFont {
return fontSize
}
override func viewWillAppear(animated: Bool) {
if var storeditems: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("items") {
items = []
for var i = 0; i<storeditems?.count; ++i {
items.append(storeditems?[i] as NSString)
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
items.removeAtIndex(indexPath.row)
NSUserDefaults.standardUserDefaults().setObject(items, forKey: "items")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
}
}
}
View Controller 2
import UIKit
class ViewController2: UIViewController, UITextFieldDelegate {
#IBOutlet weak var textField: UITextField!
#IBAction func button(sender: AnyObject) {
items.append(textField.text)
NSUserDefaults.standardUserDefaults().setObject(items, forKey: "items")
NSUserDefaults.standardUserDefaults().synchronize()
}
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.
}
/*
// 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?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
Swift and Objective-C only support single inheritance. They do support multiple protocols. Extension is principally achieved via composition.
UITableViewDelegate and UITableViewDataSource are protocols.
UIFont is not a protocol, it is a class.