SideMenuBar dont load - ios

I have a sidebar menu made with a tableview. When the user click on one cell from the sidebar, it shows a tableview with categories (check image below). The problem i'm facing is that I click on a cell from the sidebar and it loads the right viewcontroller, but if I click again it does not load, it simply knows that the column is the same one, it does nothing.
I think its a problem in the sidebar that do not load the content because it knows its the same indexPath. No? Thank you
Screen:
My Sidebar code:
import UIKit
import Parse
var opcoesSideMenu: [String] = ["Inicio","Perfil","Restaurantes","Categorias","Meu Restaurante","Sair"]
class MyMenuTableViewController: UITableViewController {
var selectedMenuItem : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Customize apperance of table view
tableView.contentInset = UIEdgeInsetsMake(64.0, 0, 0, 0) //
tableView.separatorStyle = .None
tableView.backgroundColor = UIColor.clearColor()
tableView.scrollsToTop = false
// Preserve selection between presentations
self.clearsSelectionOnViewWillAppear = false
tableView.selectRowAtIndexPath(NSIndexPath(forRow: selectedMenuItem, inSection: 0), animated: false, scrollPosition: .Middle)
}
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 the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return opcoesSideMenu.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cellmenu") as? UITableViewCell
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cellmenu")
cell!.backgroundColor = UIColor.clearColor()
cell!.textLabel?.textColor = UIColor.whiteColor()
let selectedBackgroundView = UIView(frame: CGRectMake(0, 0, cell!.frame.size.width, cell!.frame.size.height))
selectedBackgroundView.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.2)
cell!.selectedBackgroundView = selectedBackgroundView
}
// cell!.textLabel?.text = "ViewController #\(indexPath.row+1)"
cell!.textLabel?.text = opcoesSideMenu[indexPath.row] as String
if cell!.textLabel?.text == "Meu Restaurante" {
if localizacaoActualizada.temRestaurante == false {
// cell!.textLabel?.textColor = UIColorFromRGB(0x303E73)
}
}
//Vai procurar uma imagem com o mesmo nome que o que esta no array OpcoesSideMenu e colocado ao lado do texto
var imageName = UIImage(named: opcoesSideMenu[indexPath.row])
cell!.imageView?.image = imageName
return cell!
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 50.0
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if localizacaoActualizada.temRestaurante == false {
if indexPath.row == 4 {return nil}
}
return indexPath
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("Selected row: \(indexPath.row)")
if (indexPath.row == selectedMenuItem) {
return
}
selectedMenuItem = indexPath.row
//Present new view controller
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main",bundle: nil)
var destViewController : UIViewController
switch (indexPath.row) {
case 0:
destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("listarRestaurantes") as! UIViewController
break
case 1:
destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("perfilUtilizador")as! UIViewController
break
case 2:
destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("categorias")as! UIViewController
break
case 3:
destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("perfilRestaurante")as! UIViewController
break
case 4:
PFUser.logOut()
destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ViewController1") as! UIViewController
break
default:
destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("Inicio") as! UIViewController
break
}
sideMenuController()?.setContentViewController(destViewController)
}
}

Related

Custom Cell TextVIew text not changing

I am creating a simple article application in IOS using Swift. I am having issues updating the text inside of my textview. but I have the textView in a custom TableViewCell class and cannot figure out how to change the text. I have also tried making a setter function. I have no error logs, I am printing the contents of the cell after I create it and after I change the text. When I create it it has place holder text, after i change it it IS changed in the cell in cellforRow, but physically displayed is the text from the xib.
import UIKit
class ViewController2: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate {
//mydata
var articles = ["Article","Article","Article","Article","Article","Article","Article"]
var farmers = ["farmer","farmer","farmer","farmer","farmer","farmer","farmer",]
var products = ["coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee","coffee",]
var article = "I am aware that this question has been asked, but none of the answers have worked for me. I'm trying to implement a comments View controller, similar to what you can see in Instagram, where the size of the tableView cell depends on the size of the comment. So I though I would get the necessary height to display the whole comment in textView without scrolling, adjust the textView, then use it to set the heightForRowAtIndexPath appropriately, before finally reloading the table. However, I can't even get to resize the textView, I have tested a certain number of answers and still the textView won't budge."
//flags
var flag = 0 //0=article, 1 = categories, 2 = productpage
// outlets
#IBOutlet weak var tableView: UITableView!
///Default
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let nib1 = UINib(nibName: "Picture2", bundle: nil)
tableView.registerNib(nib1, forCellReuseIdentifier: "Picture2")
let nib2 = UINib(nibName: "Title", bundle: nil)
tableView.registerNib(nib2, forCellReuseIdentifier: "Title")
let nib3 = UINib(nibName: "Article", bundle: nil)
tableView.registerNib(nib3, forCellReuseIdentifier: "Article")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//TableView
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch flag
{
case 0:
return 3
case 1:
return products.count
case 2:
return farmers.count
default:
return 1
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch flag
{
case 0:
if(indexPath.row == 0)
{
return 216;
}
else if(indexPath.row == 1)
{
return 80;
}
else
{
var hieght = calculateHeightForString(article)
return hieght
}
case 1:
return 44
case 2:
return 216
default:
return 216
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch flag
{
case 0:
self.performSegueWithIdentifier("View2", sender: self)
case 1:
self.performSegueWithIdentifier("View2", sender: self)
case 2:
//self.performSegueWithIdentifier("Product", sender: self)
break
default:
return self.performSegueWithIdentifier("View2", sender: self)
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch flag
{
case 0:
if(indexPath.row == 0)
{
let cell = self.tableView.dequeueReusableCellWithIdentifier("Picture2", forIndexPath: indexPath) as! Picture2Cell
let imageName = "Bag.png"
let image = UIImage(named: imageName)
cell.Picture.image = image
return cell
}
else if(indexPath.row == 1)
{
let cell = self.tableView.dequeueReusableCellWithIdentifier("Title", forIndexPath: indexPath) as! TitleCell
cell.title.text = "THIS IS THE TTITLE"
cell.by.text = "Zach Chandler"
cell.country.text = "Camaroon"
return cell
}
else
{
var cell = self.tableView.dequeueReusableCellWithIdentifier("Article", forIndexPath: indexPath) as! ArticleCell
print(cell.textView.text)
println("Changed")
let currentText:NSString = article
cell.textView.text = currentText as String
print(cell.textView.text)
return cell
}
case 2:
let cell = self.tableView.dequeueReusableCellWithIdentifier("MainCell", forIndexPath: indexPath) as! Picture1Cell
cell.title.text = "indexpath.section \(indexPath.section)"
let imageName = "Bag.png"
let image = UIImage(named: imageName)
cell.picture.image = image
cell.subtitle.text = "indexPath.row \(indexPath.row)"
return cell
case 1:
let cell = self.tableView.dequeueReusableCellWithIdentifier("ProductCell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel!.text = products[indexPath.row]
let imageName = "bag.png"
let image = UIImage(named: imageName)
cell.imageView!.image = image
cell.detailTextLabel?.text = "indexpath.row\(indexPath.row)"
return cell
default:
let cell = self.tableView.dequeueReusableCellWithIdentifier("ProductCell", forIndexPath: indexPath) as!
UITableViewCell
cell.textLabel?.text = "indexpath.row\(indexPath.row)"
return cell
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
switch flag
{
case 0:
return 1
case 1:
return 1
case 2:
return farmers.count
default:
return 1
}
}
//segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
//personal functions
func calculateHeightForString(inString:String) -> CGFloat
{
var messageString = inString
var attributes = [UIFont(): UIFont.systemFontOfSize(15.0)]
var attrString:NSAttributedString? = NSAttributedString(string: messageString, attributes: attributes)
var rect:CGRect = attrString!.boundingRectWithSize(CGSizeMake(300.0,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context:nil )
var requredSize:CGRect = rect
return requredSize.height //to include button's in your tableview
}
article class
import UIKit
class ArticleCell: UITableViewCell, UITextViewDelegate {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
#IBOutlet weak var textView: UITextView!
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func SetText(inString: String)
{
textView.text = inString
}
Try setting the delegate before you change the text, in your cellForRowAtIndexPath method. Should be something like
cell.textView.delegate = self

Use of undeclared type "ParallaxHeaderView"

I added the ParallaxHeaderView folder but I'm getting an error saying that it undeclared.
import UIKit
class TimelineViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
let cellData = CellData()
let tableViewCellIdentifier = "tableCell"
let bottomCellIdentifier = "bottomTableCell"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let headerImage = UIImage(named: "Shreyas.png")
Getting error on this line
let headerView: ParallaxHeaderView = ParallaxHeaderView.parallaxHeaderViewWithImage(headerImage, forSize: CGSizeMake(self.view.frame.size.width, 200.0)) as! ParallaxHeaderView
// Tap Gesture to return to previous view
headerView.userInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: "headerTapped")
headerView.addGestureRecognizer(tapGesture)
// Label settings
headerView.headerTitleLabel.font = UIFont(name: "HelveticaNeue-Medium", size: CGFloat(32.0))
headerView.headerTitleLabel.text = "Shreyas Papinwar"
headerView.headerTitleLabel.frame.origin.y -= 60.0
self.tableView.tableHeaderView = headerView
tableView.dataSource = self
tableView.delegate = self
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "facebook.Segue" {
let webVC: WebViewController = segue.destinationViewController as! WebViewController
webVC.webURL = "https://facebook.com/the3seconds"
}
else if segue.identifier == "twitterSegue" {
let webVC: WebViewController = segue.destinationViewController as! WebViewController
webVC.webURL = "https://twitter.com/spapinwar"
}
else if segue.identifier == "docSegue" {
let webVC: WebViewController = segue.destinationViewController as! WebViewController
webVC.webURL = "http://github.com"
}
else if segue.identifier == "sheetSegue" {
let webVC: WebViewController = segue.destinationViewController as! WebViewController
webVC.webURL = "http://google.com"
}
else {
print("Unexpected segue identifier: \(segue.identifier)")
}
}
// MARK: - UITableViewDataSource methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return cellData.cells.count
}
else {
return 1
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier(tableViewCellIdentifier, forIndexPath: indexPath) as! TimelineTableViewCell
let entry = cellData.cells[indexPath.row]
let cellDate = entry.date
let cellLineImage = UIImage(named: entry.line)
cell.tableCellDate.text = cellDate
cell.tableCellLineImage.image = cellLineImage
cell.tableCellLabel.text = entry.labelText
return cell
}
else {
let bottomCell = tableView.dequeueReusableCellWithIdentifier(bottomCellIdentifier, forIndexPath: indexPath) as! BottomTableViewCell
return bottomCell
}
}
// MARK: - UITableView methods
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
return CGFloat(160.0)
}
else {
return CGFloat(300.0)
}
}
// MARK: - UITableViewDelegate methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
print(cellData.cells[row].labelText)
}
// MARK: UIScrollViewDelegate methods
func scrollViewDidScroll(scrollView: UIScrollView) {
let header: ParallaxHeaderView = self.tableView.tableHeaderView as! ParallaxHeaderView
header.layoutHeaderViewForScrollViewOffset(scrollView.contentOffset)
self.tableView.tableHeaderView = header
}
// MARK: - Helper methods
func headerTapped() {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
If you want to add a headerViews to your tableView? You'll need couple of UITableViewDelegate methods.
tableView:viewForHeaderInSection:
tableView:heightForHeaderInSection
And you can use XIB files for creating custom headerView. XIB files allows you more than default.

how to uncheck uitableview cells using accessory checkmark

i have two sections
1.MapViewController
2.TypesTableViewController
when i run my app and call TypesTableViewController and when it opens it shows all cells selected i want it to be unchecked
please help me and check my code
1.MapViewController
class MapViewController: UIViewController {
#IBOutlet weak var mapCenterPinImage: UIImageView!
#IBOutlet weak var pinImageVerticalConstraint: NSLayoutConstraint!
var searchedTypes = ["bakery", "bar", "cafe", "grocery_or_supermarket", "restaurant"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Types Segue" {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.topViewController as! TypesTableViewController
controller.selectedTypes = searchedTypes
controller.delegate = self
}
}
}
// MARK: - TypesTableViewControllerDelegate
extension MapViewController: TypesTableViewControllerDelegate {
func typesController(controller: TypesTableViewController, didSelectTypes types: [String]) {
searchedTypes = controller.selectedTypes.sort()
dismissViewControllerAnimated(true, completion: nil)
}
}
2.TypesTableViewController
protocol TypesTableViewControllerDelegate: class {
func typesController(controller: TypesTableViewController, didSelectTypes types: [String])
}
class TypesTableViewController: UITableViewController {
let possibleTypesDictionary = ["bakery":"Bakery", "bar":"Bar", "cafe":"Cafe", "grocery_or_supermarket":"Supermarket", "restaurant":"Restaurant"]
var selectedTypes: [String]!
weak var delegate: TypesTableViewControllerDelegate!
var sortedKeys: [String] {
return possibleTypesDictionary.keys.sort()
}
// MARK: - Actions
#IBAction func donePressed(sender: AnyObject) {
delegate?.typesController(self, didSelectTypes: selectedTypes)
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return possibleTypesDictionary.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TypeCell", forIndexPath: indexPath)
let key = sortedKeys[indexPath.row]
let type = possibleTypesDictionary[key]!
cell.textLabel?.text = type
cell.imageView?.image = UIImage(named: key)
cell.accessoryType = (selectedTypes!).contains(key) ? .Checkmark : .None
return cell
}
// MARK: - Table view delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let key = sortedKeys[indexPath.row]
if (selectedTypes!).contains(key) {
selectedTypes = selectedTypes.filter({$0 != key})
} else {
selectedTypes.append(key)
}
tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//toggle checkmark on and off
if tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark {
tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
else {
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}
//add animation so cell does not stay selected
tableView.deselectRow(at: indexPath, animated: true)
}
Not sure what you are doing in your code. If you want to uncheck then change below line to
cell.accessoryType = (selectedTypes!).contains(key) ? .Checkmark : .None
to
cell.accessoryType = (selectedTypes!).contains(key) ? . None : . Checkmark
Updated:- second part of the answer to get only checkmark cells,
change as below
#IBAction func donePressed(sender: AnyObject) {
let rowCount = tableView.numberOfRowsInSection(0)
selectedTypes.removeAll()
for var index = 0; index < rowCount; ++index {
let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) as! YourCell
if cell.accessoryType = .Checkmark{
let key = sortedKeys[index]
selectedTypes.append(key)
}
delegate?.typesController(self, didSelectTypes: selectedTypes)
}
}

Two UITableView in single UIViewcontroller not working properly

I want to implement following functionality in app show pict
But i have following problem show another pict
my code as follow
// MARK: UITextFieldDelegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if str == "Loading"{
return 0
}else if tableView == tbl2{
return arrSub.count
}else{
return self.displayData.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:customCellInvitation = self.tableView.dequeueReusableCellWithIdentifier("cell")as! customCellInvitation
if tableView == tbl2{
//Code for the load secind table
cell.lblUserName.text = self.arrSub.objectAtIndex(indexPath.row).valueForKey("username") as?String
cell.btnAdd.setImage(UIImage(named: "yes1.png"), forState:(UIControlState.Normal))
return cell
}else{
//Code for the load first table
cell.lblUserName.text = self.displayData.objectAtIndex(indexPath.row).valueForKey("username") as?String
cell.btnAdd.setImage(UIImage(named: "add.png"), forState:(UIControlState.Normal))
cell.btnAdd.setImage(UIImage(named: "yes1.png"), forState:(UIControlState.Selected))
cell.btnAdd.addTarget(self, action: "addData:", forControlEvents: .TouchUpInside)
cell.btnAdd.tag = indexPath.row
}
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
//function call when user click Plus button
func addData(sender: UIButton!) {
arrSub .addObject(self.displayData .objectAtIndex(sender.tag))
var button:UIButton = sender.viewWithTag(sender.tag) as! UIButton
button.selected=true
button.userInteractionEnabled = false
NSLog("%#", arrSub)
[tbl2 .reloadData()]
}
I would suggest you to move your tableView Datasource and Delegate to separate classes. This is not a good practise at all. You will certainly mess up with your code.
What you are doing make code complexity, you can add you own custom class for tableView and can maintain it it all delegate datasource methods.Add that tableview in current class and with giving frame to it. By this you can add as many number of tableview to a single class and no need to worry about data handling.
Put a frame to this table view, then you can add two frame to a view controller. So add this frame to your view controller, you should adjust the frame width and hight in order to show two tables.
class ViewController: UIViewController {
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .None
tableView.frame = CGRectMake(20, (self.view.frame.size.height - 54 * 5) / 2.0, (self.view.frame.size.width - 25 * 5), 54 * 5)
tableView.autoresizingMask = .FlexibleTopMargin | .FlexibleBottomMargin | .FlexibleWidth
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.opaque = false
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView = nil
tableView.bounces = false
tableView.showsVerticalScrollIndicator = true
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clearColor()
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK : TableViewDataSource & Delegate Methods
extension LeftMenuViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 54
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
let titles: [String] = ["Home", "Features", "Pricing", "Help", "About Us", "Contact Us"] // put your titles
let images: [String] = ["IconHome", "IconCalendar", "IconProfile", "IconSettings", "IconEmpty", "IconEmpty"] // add images if you want
cell.backgroundColor = UIColor.clearColor() // optional
cell.textLabel?.font = UIFont(name: "HelveticaNeue", size: 21)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.text = titles[indexPath.row]
cell.selectionStyle = .None
cell.imageView?.image = UIImage(named: images[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row {
case 0:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewControllerWithIdentifier("TabBar") as! UIViewController
sideMenuViewController?.contentViewController = viewController
sideMenuViewController?.hideMenuViewController()
break // show table navigation view controller
case 1:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewControllerWithIdentifier("TabBar") as! UIViewController
sideMenuViewController?.contentViewController = viewController
sideMenuViewController?.hideMenuViewController()
break // show table navigation view controller
default:
break
}
}
}
// MARK: UITextFieldDelegate Methods
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:customCellInvitation = self.tableView.dequeueReusableCellWithIdentifier("cell")as! customCellInvitation
if tableView == tbl2{
cell.lblUserName.text = self.arrSub.objectAtIndex(indexPath.row).valueForKey("username") as?String
if str = "yes"{
cell.btnAdd.setImage(UIImage(named: "yes1.png"), forState:(UIControlState.Normal))
}else{
cell.btnAdd.setImage(UIImage(named: "NO.png"), forState:(UIControlState.Normal))
}
return cell
}else{
cell.lblUserName.text = self.displayData.objectAtIndex(indexPath.row).valueForKey("username") as?String
if str = "yes"{
cell.btnAdd.setImage(UIImage(named: "yes1.png"), forState:(UIControlState.Normal))
}else{
cell.btnAdd.setImage(UIImage(named: "NO.png"), forState:(UIControlState.Normal))
}
}
return cell
}

Are there some optional wrong here?

This is the code and the problem
There is no wrong when I did select one row before I add the function tableView(......didSelectRowatindexPath...)
So, I thought it's the root cause.
I hope somebody can help me because the wrong info was not so clear that I can understand it well.
What I want to do is change the BarItemName when I did select one row of my popover table.
SwitchA is a var in my popoverviewcontroller, it means which button is pressed.
When the button in "SecondVC" is pressed,it will pass a value to SwitchA and then the popoverviewcontroller can determine which datasource it should show.
PS:this is the popoverviewcontroller's code.
import UIKit
class PopOverView: UIViewController, UITableViewDataSource, UITableViewDelegate {
var SwitchA = 0
var ClassA = ["这个类型","那个类型","这个类型","那个类型","这个类型","那个类型","这个类型","那个类型","这个类型","那个类型"]
var TimeA = ["昨天","今天","明天","昨天","今天","明天"]
var TagA = ["动漫","音乐","游戏","音乐","游戏"]
#IBOutlet weak var TV: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
TV.dataSource = self
TV.delegate = self
self.preferredContentSize = CGSize(width: UIScreen.mainScreen().bounds.width, height: 175)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if SwitchA == 0 {
return ClassA.count
}
if SwitchA == 1 {
return TimeA.count
}
else {
return TagA.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
if SwitchA == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = ClassA[indexPath.row]
cell.separatorInset = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsetsZero
return cell
}
if SwitchA == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = TimeA[indexPath.row]
cell.separatorInset = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsetsZero
return cell
}
else {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = TagA[indexPath.row]
cell.separatorInset = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsetsZero
return cell
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 35.0
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if SwitchA == 0 {
let VC = self.storyboard!.instantiateViewControllerWithIdentifier("SecondVC") as! XiaoNei_HuoDong
VC.ClassName.title = ClassA[indexPath.row]
}
if SwitchA == 1 {
let VC = self.storyboard!.instantiateViewControllerWithIdentifier("SecondVC") as! XiaoNei_HuoDong
VC.TimeName.title = TimeA[indexPath.row]
}
else {
let VC = self.storyboard!.instantiateViewControllerWithIdentifier("SecondVC") as! XiaoNei_HuoDong
VC.TagName.title = TagA[indexPath.row]
}
}
/*
// 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.
}
*/
}
And this is the code of "SecondVC":
import UIKit
class XiaoNei_HuoDong: UIViewController,UITableViewDelegate,UITableViewDataSource, UIPopoverPresentationControllerDelegate{
#IBOutlet weak var TagName: UIBarButtonItem!
#IBOutlet weak var TimeName: UIBarButtonItem!
#IBOutlet weak var ClassName: UIBarButtonItem!
#IBOutlet weak var huodongTV: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
huodongTV.dataSource = self
huodongTV.delegate = self
huodongTV.showsVerticalScrollIndicator = false
let options = PullToRefreshOption()
options.backgroundColor = UIColor(red: 239/255, green: 239/255, blue: 244/255, alpha: 1)
options.indicatorColor = UIColor.blackColor()
huodongTV.addPullToRefresh(options: options, refreshCompletion: { [weak self] in
// some code
self!.huodongTV.reloadData()
self!.huodongTV.stopPullToRefresh()
})
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return 3
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 1.0
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1.0
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
self.huodongTV.deselectRowAtIndexPath(indexPath, animated: false)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
if indexPath.row == 0 {
let cell:HuoDong_2 = tableView.dequeueReusableCellWithIdentifier("huodong2") as! HuoDong_2
cell.ClubB1.image = UIImage(named: "test")!
cell.ClubB2.image = UIImage(named: "test")!
cell.ClubS1.image = UIImage(named: "focus")!
cell.ClubS2.image = UIImage(named: "focus")!
cell.Tag1.image = UIImage(named: "更新")!
cell.Tag2.image = UIImage(named: "更新")!
cell.View1.image = UIImage(named: "view")!
cell.View2.image = UIImage(named: "view")!
cell.Newest.image = UIImage(named: "club rank")
return cell
}
else {
let cell:HuoDong = tableView.dequeueReusableCellWithIdentifier("huodong1") as! HuoDong
cell.ClubB1.image = UIImage(named: "test")!
cell.ClubB2.image = UIImage(named: "test")!
cell.ClubS1.image = UIImage(named: "focus")!
cell.ClubS2.image = UIImage(named: "focus")!
cell.Tag1.image = UIImage(named: "更新")!
cell.Tag2.image = UIImage(named: "更新")!
cell.View1.image = UIImage(named: "view")!
cell.View2.image = UIImage(named: "view")!
return cell
}
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath){
cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1)
UIView.animateWithDuration(0.25, animations: {
cell.layer.transform = CATransform3DMakeScale(1, 1, 1)
})
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return self.view.frame.width * 240.0 / 400.0
}
else {
return self.view.frame.width * 200.0 / 400.0
}
}
// MARK: - PopOverforsegue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Class1"{
let VC = segue.destinationViewController as! PopOverView
VC.SwitchA = 0
VC.modalPresentationStyle = UIModalPresentationStyle.Popover
VC.popoverPresentationController?.delegate = self
}
if segue.identifier == "Time1"{
let VC = segue.destinationViewController as! PopOverView
VC.SwitchA = 1
VC.modalPresentationStyle = UIModalPresentationStyle.Popover
VC.popoverPresentationController?.delegate = self
}
if segue.identifier == "Tag1"{
let VC = segue.destinationViewController as! PopOverView
VC.SwitchA = 2
VC.modalPresentationStyle = UIModalPresentationStyle.Popover
VC.popoverPresentationController?.delegate = self
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
/*
// 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.
}
*/
}
I think problem is timing of initialize.
Try this:
SecondVC
var tagNameStr = ""
override func viewDidLoad() {
super.viewDidLoad()
TagName.title = tagNameStr // here
...
}
FirstVC
if SwitchA == 0 {
let VC = self.storyboard!.instantiateViewControllerWithIdentifier("SecondVC") as! XiaoNei_HuoDong
VC.tagNameStr = ClassA[indexPath.row]
}
Hope this helps!
UPDATE
This is sample code.
(ViewController -|segue|-> SecondViewController)
class ViewController: UIViewController {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let vc = segue.destinationViewController as? SecondViewController {
vc.buttonTitle = "IOhYES"
}
}
}
class SecondViewController: UIViewController {
#IBOutlet weak var buttonItem: UIBarButtonItem!
var buttonTitle = ""
override func viewDidLoad() {
super.viewDidLoad()
buttonItem.title = buttonTitle
}
}
Please check IBOutlet connection.

Resources