dimanche 31 mai 2015

How to create category and subcategory selection in UITableView in iOS Objective-C

I want to create a table view with category and subcategory selection in UITableView with Objective-C for iOS but I do't know what to search and from were to start. The content of the category and subcategory are dynamic it can be one or more then it will be decided by web service result. and all category should be collapse on tap. It should look like this. enter image description here

Any suggestion and help will be appreciated

Edit #1

I have tried something but not working fine here is the code for what i have tried yet. Interest (Category and Subcategory)

See more ..

iOS Swift: Displaying asynchronous data on a TableView

I have a ViewController with a TableView in it, now the data for TableView is pulled via an http call asynchronously in another class.

class ViewController1: UIViewController, UITableViewDelegate, UITableViewDataSource {

    override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

            MyHttpClass().getData()//INITIATING getting data asynchronously
...
}

MyHttpClass gets the data after a few seconds asynchronously, but it does not have a reference of the ViewController to hand over the data (ideally the ViewController.tableView.reloadData - is what i need to call)

Is there a better way to handle this? How do i get ref. to ViewController instance when MyHttp gets the data? Any better way to handle this?

See more ..

scene is unreachable due to a lack of entry points.. no identifier for runtime access?

This question has been asked & addressed before but i haven't found a solution that fixes my issue. why am i getting this "scene is unreachable due to a lack of entry points and does not have an identifier for runtime access via - instantiateViewControllerWithIdentifier" error? when i run the app, after the launching image, it just turns black & the debugger has the following message:

enter image description here

my default TableViewController (which is my 1st) is instantiated with the following code within:

import UIKit

class FirstTableViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

}

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 Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 21
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell


    return cell
}

}

and my following two tableViewControllers are also instantiated. all segues in my storyboard have identifiers as well. what seems to be the issue?

See more ..

Implement Search bar and search display for the table view with sections

I am trying to implement search bar with search display feature in swift for the table view given below.

Screenshot of the table view

enter image description here

I am getting issue because my string array is in the following format.

["section name1" : ["list1", "list2"] ,"section name2" : ["list3", "list4"]]

I have added my code below for the table view.

    @IBOutlet weak var dishtable: UITableView!

@IBOutlet weak var namlbl: UILabel!
var Dishes = ["POPULAR Dishes": ["Biryani", "Tandori Chicken","Butter Chicken", "Vada Pav"],"A": ["Aloo baingan", "Aloo ki Tikki", "Amritsari fish"], "B": ["Baigan bharta", "Biryani"]];

var Filterval = ["POPULAR Dishes": ["Biryani", "Tandori Chicken","Butter Chicken", "Vada Pav"],"A": ["Aloo baingan", "Aloo ki Tikki", "Amritsari fish"], "B": ["Baigan bharta", "Biryani"]];

struct dish {
    let Dish : [String]
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.dishtable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    dishtable.dataSource = self
    dishtable.delegate = self
    // Do any additional setup after loading the view.
}


func filterContentForSearchText(searchText: String) {
    // Filter the array using the filter method
    self.Filterval = self.Dishes.filter({( d: dish) -> Bool in
        let DishMatch = (d.Dish == scope)
        let stringMatch = d.Dish.rangeOfString(searchText)
        return DishMatch && (stringMatch != nil)
    })
}

func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
    self.filterContentForSearchText(searchString)
    return true
}

func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchScope searchOption: Int) -> Bool {
    self.filterContentForSearchText(self.searchDisplayController!.searchBar.text!)
    return true
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool {
    return true
}

let sections:Array<AnyObject> = ["POPULAR Dishes","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
var usernames = [String]()

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

    let cellID = "cell"

    let cell: UITableViewCell =  self.dishtable.dequeueReusableCellWithIdentifier(cellID) as! UITableViewCell
    println("value : \(indexPath.section)")
    println("value 1: \(indexPath.row)")
     var d : dish
    if tableView == self.searchDisplayController!.searchResultsTableView {

        cell.textLabel!.text = Filterval[sections[indexPath.section] as! String]![indexPath.row]

    } else {

        cell.textLabel!.text = Dishes[sections[indexPath.section] as! String]![indexPath.row]
    }


    return cell

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    println("Dishes section count : \(section)")
    if tableView == self.searchDisplayController!.searchResultsTableView {
        if section == 0 {
            return Filterval["POPULAR Dishes"]!.count
        }
        else if section == 1 {
            return Filterval["A"]!.count
        }
        else if section == 2 {
            return Filterval["B"]!.count
        }
        else if section == 3 {
            return Filterval["C"]!.count
        }
        else if section == 4 {
            return Filterval["D"]!.count
        }
        else if section == 5 {
            return Filterval["E"]!.count
        }
        else if section == 6 {
            return Filterval["F"]!.count
        }
        return 0
    } else {
    if section == 0 {
        return Dishes["POPULAR Dishes"]!.count
    }
    else if section == 1 {
        return Dishes["A"]!.count
    }
    else if section == 2 {
        return Dishes["B"]!.count
    }
    else if section == 3 {
        return Dishes["C"]!.count
    }
    else if section == 4 {
        return Dishes["D"]!.count
    }
    else if section == 5 {
        return Dishes["E"]!.count
    }
    else if section == 6 {
        return Dishes["F"]!.count
    }
    return 0

    }
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int{

    return 27
}

func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

}


func tableView(tableView: UITableView,
    sectionForSectionIndexTitle title: String,
    atIndex index: Int) -> Int{

        return index
}

func tableView(tableView: UITableView,
    titleForHeaderInSection section: Int) -> String?{

        return self.sections[section] as? String
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    var ban = ""

    ban = Dishes[sections[indexPath.section] as! String]![indexPath.row]

    println(ban)


}

I have tried the following links online, but unable to implement the search feature.

  1. http://ift.tt/1D32mxT

  2. http://ift.tt/1HweLgu

  3. http://ift.tt/1vh1XX9

Can someone help me with search bar?

See more ..

A better way to implement margins in a UITableView?

Apple has deprecated margins in table views, since iOS7, but designers still seem to want margins. What’s the best way t implement margins in iOS 7 and above? The old “group” table view style that included margins in iOS 6 no longer indents the left and right edges.

I have a UITableView subclass, in which i’m using the following method to programmatically add margins to the edge of all subviews, except the backgroundView (such as cells, section header etc):

- (void)layoutSubviews {
[super layoutSubviews];
for (UIView *subview in self.subviews) {
    if (subview != self.backgroundView && subview.frame.origin.x == 0.0 && subview.frame.size.width == self.frame.size.width) {
        subview.frame = CGRectInset(subview.frame, 10.0, 0);
    }
}

}

During runtime, it all seems to work as desired. The cells resize according to the margin offset and the subviews of those cells adjust correctly. However, in the storyboard, using IBDesignable, the cells adjust correctly but the cells’ subviews do not seem to resize within the cell’s calculated size

Is there a better way to implement margins in a UITableView?

Thanks c:

See more ..

UITableViewCell auto-sizing height not working

The cells in my table view are not auto-sizing their height to contain the content. I am using the "Basic" style for the cell prototype. I created a new test project containing only my view controller and a storyboard and it has the same issue. What am I doing wrong?

RowHeightTestController:

@implementation RowHeightTestController

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Test" forIndexPath:indexPath];

    // Configure the cell...
    cell.textLabel.text = @"Testing";
    cell.textLabel.font = [UIFont systemFontOfSize:60 + indexPath.row];

    return cell;
}

@end

The storyboard:

Storyboard

What I am seeing:

enter image description here

See more ..

I'm trying to populate a tableview with a list of users, but the tableview will not load anything

For some reason I keep getting back a blank tableview. It is showing a query is being loaded from Parse, it just isn't displaying any results. Thanks in advance for your help.

class userViewController: PFQueryTableViewController {


    override init(style: UITableViewStyle, className: String!) {
        super.init(style: style, className: className)

    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.pullToRefreshEnabled = true

    }
    override func queryForTable() -> PFQuery {
        var query: PFQuery = PFUser.query()!
        println(query)
        return query
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject!) -> PFTableViewCell {

        var userCell = tableView.dequeueReusableCellWithIdentifier("Cell2") as! PFTableViewCell!

        if userCell == nil {
            userCell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell2")
        }

        if let lastName = object["lastName"] as? String {
            var firstName = object["firstName"] as? String
            userCell?.textLabel?.text = "\(lastName), \(firstName)"

        }
        if let adminStatus = object["adminStatus"] as? Bool {
            if adminStatus == true {
            userCell?.detailTextLabel?.text = "Administrative Privliges"
            }else{
            userCell?.detailTextLabel?.text = "Non Administrative Privliges"
            }
        }

        return userCell
    }

    override func viewWillAppear(animated: Bool)
    {
        self.navigationController?.navigationBarHidden = false
    }
}

See more ..

iOS 8 - Uitableviewcell edit items not displaying when swiped

I have a custom UITableViewCell where everything is displaying correctly and I am able to swipe each row to the left. On an iPad, everything works fine. However on any model of iPhone, rather than display the two edit actions as defined in the code below, nothing is displayed. The row simply slides to the left, leaving nothing where the edit buttons should be.

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
    let thing = things![indexPath.row]

    var editAction = UITableViewRowAction(style: .Default, title: "Edit") { (action, indexPath) -> Void in
        tableView.editing = false
        self.editThing = thing
        self.performSegueWithIdentifier("thingEdit", sender: self)
    }
    editAction.backgroundColor = UIColor.grayColor()

    var deleteAction = UITableViewRowAction(style: .Normal, title: "Delete") { (action, indexPath) -> Void in
        tableView.editing = false
        self.deleteThing(indexPath)
    }
    deleteAction.backgroundColor = UIColor.redColor()

    return [editAction, deleteAction]
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}

I am using essentially exactly the same code elsewhere and it works fine on all devices. I have confirmed that there are no visible differences between the definition of the working and non-working tables in the storyboard.

See more ..

Populate array of custom classes from two different network requests

In my Swift iOS project, I am trying to populate an array of custom class objects using JSON data retrieved with Alamofire and parsed with SwiftyJSON. My problem, though, is combining the results of two different network request and then populating a UITableView with the resulting array.

My custom class is implemented:

class teamItem: Printable {
var name: String?
var number: String?

init(sqljson: JSON, nallenjson: JSON, numinjson: Int) {
    if let n = sqljson[numinjson, "team_num"].string! as String! {
        self.number = n
    }
    if let name = nallenjson["result",0,"team_name"].string! as String! {
        self.name = name
    }

}

var description: String {
    return "Number: \(number) Name: \(name)"
}
}

Here is my viewDidLoad():

    override func viewDidLoad() {
    super.viewDidLoad()


    tableView.dataSource = self
    refresh() {
        () -> Void in
            self.tableView(self.tableView, numberOfRowsInSection: self.teamsArr.count)
            self.tableView.reloadData()
        for item in self.teamsArr {
            println(item)
        }
            return
        }
    self.tableView.reloadData()
    }

which goes to the refresh() method:

func refresh(completionHandler: (() -> Void)) {
    populateArray(completionHandler)
}

and finally, populateArray():

    func populateArray(completionHandler: (() -> Void)) {
    SqlHelper.getData("http://ift.tt/1ADGU8F", params: ["team_num":"ALL"]) {
        (result: NSData) in
        let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(result, options: NSJSONReadingOptions.MutableContainers, error: nil)
        let json = JSON(jsonObject)
        self.json1 = json
        println(json.count)
        for var i = 0; i < json.count; ++i {
            var teamnum = json[i,"team_num"].string!
            NSLog(teamnum)
            Alamofire.request(.GET, "http://ift.tt/StO6yC", parameters: ["team": teamnum])
                .responseJSON { (req, res, json, err) in
                    let json = JSON(json!)
                    self.json2 = json
                        self.teamsArr.append(teamItem(sqljson: self.json1, nallenjson: self.json2, numinjson: i))
            }
        }
        completionHandler()
    }
}

the first problem I had was that i in the for loop reached 3 and caused errors when I thought it really shouldn't because that JSON array only contains 3 entries. My other main problem was that the table view would be empty until I manually triggered reloadData() with a reload button in my UI, and even then there were problems with the data in the tables.

really appreciate any assistance, as I am very new to iOS and Swift and dealing with Alamofire's asynchronous calls really confused me. The code I have been writing has grown so large and generated so many little errors, I thought there would probably be a better way of achieving my goal. Sorry for the long-winded question, and thanks in advance for any responses!

See more ..

MvxTableViewCell not disposed

I have a memory leaks issue.

I basically have a MvxTableViewController databound to a observablecollection. I create a MvxTableViewController and add it to my Controller as a child and I add the view as a subviews.

Problem is, the Cell in the table never gets disposed, leaking memory.

// When the view gets removed from the stack, the cells disposed method is never called and I can see the memory not going away, using the Xcode Instruments tool.  The table dispose gets called as expected. but not the cell
public partial class ParticipantTableViewCell : MvxTableViewCell
{
    readonly UILabel _nameLabel = new UILabel();
    readonly UILabel _locationLabel = new UILabel();
    readonly PictureContainer _pictureView = new PictureContainer(7.0f);

    public ParticipantTableViewCell (IntPtr handle) : base(handle)
    {
        BackgroundColor = UIColor.Clear;
        SelectionStyle = UITableViewCellSelectionStyle.None;

        ContentView.AddSubviews(new UIView[] {_nameLabel, _locationLabel, _pictureView});
        _pictureView.TransparentBackground = true;

        SetupConstraints();

        // Since this view is readonly, I've removed the actual binding code
        // and instead manually init each views.
        this.DelayBind(() => {
            _nameLabel.Text = ((ParticipantViewModel)DataContext).Name;
            _locationLabel.Text = ((ParticipantViewModel)DataContext).Location;
            IsSelected = ((ParticipantViewModel)DataContext).IsSelected;
            _pictureView.AvatarImage.Image = UIImage.FromFile ("Media/" + ((ParticipantViewModel)DataContext).AvatarUrl);
        });
    }

    void SetupConstraints ()
    {
        ContentView.Subviews.ForEach(v => v.TranslatesAutoresizingMaskIntoConstraints = false);

        ContentView.AddConstraints(
            _pictureView.Height().EqualTo().HeightOf(ContentView),
            _pictureView.Width().EqualTo().HeightOf(ContentView),
            _pictureView.WithSameCenterY(ContentView),
            _pictureView.Left().EqualTo(6.0f).LeftOf(ContentView),

            _nameLabel.Left().EqualTo(10.0f).RightOf(_pictureView),
            _nameLabel.Right().EqualTo().RightOf(ContentView),
            _nameLabel.Bottom().EqualTo(2.0f).CenterYOf(ContentView),

            _locationLabel.Left().EqualTo(10.0f).RightOf(_pictureView),
            _locationLabel.Right().EqualTo().RightOf(ContentView),
            _locationLabel.Top().EqualTo(4.0f).CenterYOf(ContentView)

        );
    }

    // never called
    protected override void Dispose (bool disposing)
    {
        base.Dispose(disposing);
    }

}

    class FriendsView : MvxTableViewController
{
    protected new FriendsViewModel ViewModel { get { return (FriendsViewModel) base.ViewModel; } }

    public FriendsView ()
    {
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad();
        TableView.BackgroundColor = UIColor.Clear;
        TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
        TableView.RowHeight = 60;
        TableView.ScrollEnabled = false;

        var source = new MvxSimpleTableViewSource(TableView, typeof(ParticipantTableViewCell));
        TableView.Source = source;

        var set = this.CreateBindingSet<FriendsView, FriendsViewModel>();
        set.Bind(source).To(vm => vm.YuFitFriends);
        set.Apply();
    }
}

Anybody got an idea as to why my cells are leaking ?

thanks pat

See more ..

Passing information to a custom TableViewCell - Swift

The problem is this: I tried many ways to pass down information to a ViewController1 from a SecondViewController. In this first ViewController1 I have a tableView, and in this tableView, each cell will receive an image and a label. What I want to do is, in the SecondViewController, I will write something in a textField and pick some random image and display it in the ViewController1.

Could someone tell me how to do it? I tried delegates, dequeuereusablecell and the data won't display in the cell.

Thanks in advance!

See more ..

How to programmatically position and size subviews into cell's contentView

I would like to get the cell frame at tableView:cellForRowAtIndexPath: in order to position and size the views that I want to add to UITableViewCell's contentView.

In the example at Programmatically Adding Subviews to a Cell’s Content View they add some views using hardcoded frames like:

mainLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 220.0, 15.0)];

I guess that example is outdated, since they should use constraints, or at least calculate the size of subviews using the actual cell frame.

Anyway, how can I know the real frame of the cell when creating it?

I know the right frame is set in layoutSubviews, but if I add the subviews there it would be done every time the cell is reused, not only once.

Note: this reminds me of the view holder design pattern used in Android.

See more ..

Dynamic Cell Height autolayout IOS

I have been following this tutorial to implement dynamic cell height. dynamic-table-view-cell-height But it only works in ios 7 for me and not in ios 8. However it does work in ios 8 on the iPAD so I'm a little stumped why it doesn't work on the iphone. Whilst I have followed the code pretty exactly there are a couple of differences between the tutorial and the way I have implemented it and as I don't know enough about autolayout and tables I'm not sure if this is what is causing my problem.

Firstly on the tutorial the tableView has trailing and leading edges exactly equal to 0 to the superview. In my implementation I have created proportional constraints so that I scale the tableView within multiple different layouts. To explain further:

Here is a picture of my TableView using proportional constraints across multiple different devices. enter image description here

To achieve this I implemented the following constraints: enter image description here

enter image description here

enter image description here

enter image description here

Is it possible that the cell height cannot be calculated by AutoLayout because the tableView has a dynamic height?

The second difference that I can see between my implementation and the tutorial is the data source. I am taking my data from a call to an SLQ3Lite database whereas the tutorial is taking its data from an xml feed. I am confident that the data is populating the cells because when I look at my implementation on an IPAD I can see the data like so: enter image description here

But on an iphone this is what appears: The table is visible but no cells have been written to the table. enter image description here

When I use the debugger I can see that records are being successfully retrieved from the database, but they are not being written to the table.

Here is the code which is very long (Sorry)

    #import "favouritedViewController.h"
#import "DBManager.h"
#import "favouritedCell.h"

@interface favouritedViewController ()
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *favourites;
@property (nonatomic, strong) DBManager *dbManager;
typedef void (^CompletionBlock)();

-(void)loadData;
-(void)reloadDataWithCompletions:(CompletionBlock)completionBlock;

@end

@implementation favouritedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.dbManager = [[DBManager alloc] initWithDatabaseFilename:@"tomhaisdb.sql"];

    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    [self loadData];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)loadData {
    NSString *query = @"select * from favourites";

    if (self.favourites != nil) {
        self.favourites = nil;
    }

    self.favourites = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];

   /* [self reloadDataWithCompletions:^{
         self.tableView.backgroundColor = [UIColor colorWithRed:28.0f/255.0f green:30.0f/255.0f blue:35.0f/255.0f alpha:1];
    }];*/
    [self reloadTableViewContent];
}



/*-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}*/

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.favourites.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self basicCellAtIndexPath:indexPath];
}

- (void)reloadTableViewContent {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
    });
}

-(favouritedCell *)basicCellAtIndexPath:(NSIndexPath *)indexPath {
    favouritedCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"favouriteCell" forIndexPath:indexPath];
    [self configureBasicCell:cell atIndexPath:indexPath];
    return cell;
}

-(void)configureBasicCell:(favouritedCell *)cell atIndexPath:(NSIndexPath *)indexPath{
    NSInteger indexOfTomhaisText = [self.dbManager.arrColumnNames indexOfObject:@"tomhaisText"];
    NSString *tomhaisText = [[self.favourites objectAtIndex:indexPath.row] objectAtIndex:indexOfTomhaisText];
    [self setTomhaisForCell:cell item:tomhaisText];
    [self setAnswerForCell:cell item:tomhaisText]; // change this later
}

-(void)setTomhaisForCell:(favouritedCell *)cell item:(NSString *)item{
    [cell.favouriteText setText:item];
}

-(void)setAnswerForCell:(favouritedCell *)cell item:(NSString *)item{
    [cell.answer setText:item];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self heightForFavouriteCellAtIndexPath:indexPath];
}

-(CGFloat)heightForFavouriteCellAtIndexPath:(NSIndexPath *)indexPath{
    static favouritedCell *sizingCell = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sizingCell = [self.tableView dequeueReusableCellWithIdentifier:@"favouriteCell"];
    });

    [self configureBasicCell:sizingCell atIndexPath:indexPath];
    return [self calculateHeightForConfiguredSizingCell:sizingCell];
}

-(CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell{
    sizingCell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tableView.frame), CGRectGetHeight(sizingCell.bounds));
    [sizingCell setNeedsLayout];
    [sizingCell layoutIfNeeded];

    CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return size.height + 1.0f;
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 155.0f;
}

See more ..

SWRevealController Hanging

When I segue from a rear menu cell via "SWRevealViewControllerSeguePushController" to a UITableViewController, the animation starts quickly but then hangs but the app doesn't crash, the UI is unaccessible via touch and doesn't react anymore.

When instead I use a UIViewController it works perfectly. The as soon as I add again a UITableView in the UIViewController, it crashes again.

So basically, when using with a UIViewController it works, when using either with UITableViewController or nest UITableView in a UIViewController it hangs.

Any Help? Vince

See more ..

Create custom UITableViewCell with sliding object

I am in need of creating my own custom UITableViewCell. Within each cell, I want to have a view which basically is a switch. The switch is going to have a label on it and the user is supposed to be able to swipe right to move the switch to the right and swipe left to move the switch to the left. I have drawn a very simple prototype picture which you can see here: Pictures (Basically the blue part is supposed to be moved right and left with swipes)

I have managed to do it the simple way. Creating a view, containing another square view, adding a gesture to this view and then move it using an animation.

The problem is that if I try to add this view to the custom UITableViewCell, nothing happens.

Any tips or ideas are appreciated.

See more ..

The multiple select checkboxes of Custom UITableviewcell is not selecting

I use below code for sending my uitableview cell to editing mode:

- (UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 3;
}

when I enable editing mode the checkboxes of editing mode appears in my cells but when I click on the cells only the background changes, the checkbox not selecting or deselecting.

Please see below image: enter image description here

Does anyone have any idea about what is wrong??

I set the selectionStyle of the cells like below:

    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];

now, checkboxes is checking but when the cell is more higher, a line is adding to center of cell too!!

enter image description here

See more ..

objc - UITableView Title too wide.. What are my options?

I have a UITableView where I would like to set the tableView title to a wide label.

I'm trying to do something like: "Daily Schedule - Long Station Name"

Ideally, this would mean a title and a subTitle. As there isn't a subtitle field, is there anyway to display a wide label?

Please note that I am not asking about UITableView Section Headers.

This is about the TableView self.title. Thanks

See more ..

Passing String Value of a NSManagedObject attribute to a new view controller

I have a tableView populated with NSString values from an NSFetchedResultsController. I have the cells configured to check/uncheck cells. That works perfectly.

I'm trying to configure the cells so clicking one of the labels within the cell triggers a segue to another view controller. I configured the label and threw a log statement in where I'd like to do the segue and everything works properly. When I add the segue, get no compiler errors, but it crashes at runtime with the follow error:

2015-05-31 08:09:04.656 MyApp[17682:1240919] -[UIViewController selectedItemPhoto:]: unrecognized selector sent to instance 0x7fa42b65d4e0
2015-05-31 08:09:04.694 MyApp[17682:1240919] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController selectedItemPhoto:]: unrecognized selector sent to instance 0x7fa42b65d4e0'

I'm fairly certain I'm doing something startlingly stupid, but I'm stumped as to what. I welcome suggestions.

MyCustomCell.h:

@property (strong, nonatomic) IBOutlet UILabel *itemDescription;
@property (strong, nonatomic) IBOutlet UILabel *itemGroup;
@property (strong, nonatomic) IBOutlet UIImageView *itemImage;

FirstVC.m methods:

cellForRowAtIndexPath method

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // implement custom cell
    MyCustomCell *customCell = [tableView dequeueReusableCellWithIdentifier:@"customCell" forIndexPath:indexPath];

    // Get a hold of myManagedObject from FRC
    MyNSManagedObject *myObject = [self.fetchedResultsController objectAtIndexPath:indexPath];

    // Configures 1st label to look like a hyperlink
    customCell.itemDescription.text = myObject.itemDescription;
    customCell.itemDescription.textColor = [UIColor blueColor];
    customCell.itemDescription.userInteractionEnabled = YES;

    // Enables gesture and sets demoObject to pass along via the segue called from labelTap
    UITapGestureRecognizer *labelTapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelTap)];
    [customCell.itemDescription addGestureRecognizer:labelTapGesture];
    self.demoObject = myObject;

    // Configures 2nd label within customCell
    customCell.itemGroup.text = myObject.itemGroup;
    // add image to cell, already imported into Images.xcassets
    NSString *imageName = [NSString stringWithFormat:@"%@-1.jpg", myObject.photo];
    customCell.imageView.image = [UIImage imageNamed:imageName];

    // The following code ensures random checkmarks don't appear when the user scrolls.
    if ([self.selectedObjects containsObject:[self.fetchedResultsController objectAtIndexPath:indexPath]]) {
        customCell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        customCell.accessoryType = UITableViewCellAccessoryNone;
    }

    return customCell;
}

didSelectRowAtIndexPath method

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    self.selectedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];

    // Set the checkmark accessory for the selected row.
    if ([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryNone) {
        [[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark];
        [self.selectedObjects addObject:self.selectedObject];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    } else {
        [[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone];
        [self.selectedObjects removeObject:self.selectedObject];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }

    // Enables save button if there are items in the selectedObjects array
    if (self.selectedObjects.count > 0) {
        [self.saveButton setEnabled:YES];
    } else {
        [self.saveButton setEnabled:NO];
    }   
}

labelTap method

- (void) labelTap {
    // The "hyperlink" effect I'm trying to achieve works without the segue
    NSLog(@"itemDescription tapped");
    [self performSegueWithIdentifier:@"mySegue" sender:nil];
}

prepareForSegue method

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"mySegue"] && self.demoObject != nil) {
        // This line returns a value...
        NSLog(@"self.demoObject = %@", self.demoObject.itemDescription);
        // ...but it crashes here when it tries to set on the destinationViewController
        SecondViewController *destinationViewController = [segue destinationViewController];
        destinationViewController.selectedItemPhoto = self.demoObject.photo;
        destinationViewController.selectedItemTitle = self.demoObject.itemDescription;
    }
}

SecondViewController.h properties

// The photo is a string that references a filename in my app
@property (nonatomic, strong) NSString *selectedItemPhoto;
@property (nonatomic, strong) NSString *selectedItemTitle;

See more ..

Inserting rows on a static UITableView

I'm trying to add a row to a static table, but I'm getting this error:

2015-05-31 13:53:13.153 notify[30565:6091085] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 2 beyond bounds [0 .. 1]'

I have an @IBAction (connected to a UINavigationItem) to add the row:

@IBAction func addRow(sender: AnyObject) {
    let indexPath = NSIndexPath(forRow: rowCount, inSection: 0)
    rowCount += 1
    rowAdded = true

    tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}

with attributes for the rowCount (default in the IB design), and a bool to work out if the next row has been added yet:

class NotifyTableViewController: UITableViewController {
  var rowCount = 2
  var rowAdded = false
  ...
}

The table has 1 section, and its numberOfRowsInSection: method I've added:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  if rowAdded {
    return 3
  }else {
    return 2
  }
}

and finally, cellForRowAtIndexPath:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if indexPath.row == 2 {
        var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("customCell") as? UITableViewCell

        if cell == nil {
            cell = UITableViewCell(style: .Default, reuseIdentifier: "customCell")
            cell.textLabel!.text = "New Cell"
        }

        return cell
    }else {
        return super.tableView(tableView, cellForRowAtIndexPath: indexPath)
    }
}

I've tried wrapping the insertRowsAtIndexPaths call in begin/endUpdates, but I get the same error. Any idea what the problem is?

See more ..

UILabel position changes in relation to text length

I'm trying to create similar transition from table view to detail as here, however my nameLabel is aligned to left, next to imageview like this:

tableview

I've created custom segue with no animation, and all work is done in DetailViewController. In viewDiDload() I'm setting initial position of elements and then animate the transition with UIView.animateWithDuration(...).

I've set initial position of nameLabel like this:

self.nameLabel.frame = CGRectMake(-30, CGFloat(self.yOrigin! - 84),
    self.nameLabel.frame.size.width, self.nameLabel.frame.size.height)

and it's position at the end of animation is like this:

self.nameLabel.frame = CGRectMake(35, 50,
    self.nameLabel.frame.size.width, self.nameLabel.frame.size.height)

Problem is with position in x-axis at the beginning of animation. It's never positioned in same place, even though it is specified. It changes with text length - short text is ok, but long text gets moved to the left, and if it's very long, beginning of text is not even visible. How can I fix this?

See more ..

How to pass multiple selected UITableview cells into a separate view so the user sees the selected data

i am completely new to passing data but try to achieve that when user has selected multiple UITableView cells and the button clicked it takes each cells image and text value to any separate view controller. I try to achieve i order overview.I am looking fro any useful help via tutorials or any kind of help offered.

Thanks for your kind help to a total beginner

See more ..

xcode - UiTableView label word wrap

I define with a separate UILabel Class the margin from my Label in the Cell:

- (void)drawTextInRect:(CGRect)rect {
UIEdgeInsets insets = {5, 10,5, 10};
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)]; }

With following code, I define the height from the cell:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

if (!self.customCell) {
    self.customCell = [self.chatTableView dequeueReusableCellWithIdentifier:@"CellChat"];
}

self.customCell.sender.text = [array objectAtIndex:indexPath.row];

[self.customCell layoutIfNeeded];

CGFloat height = [self.customCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;


return height +1; }

My question: When I test the application then it will not take the word wrap on the right place. Why? Does it have something to do with the UILabel Class?

See more ..

How to repeat the data from array Start data up to End data and again Start data in IOS objective c

I want to repeat the data while loading from array Start data up to End data and again Start data in IOS objective c. I have implemented the following code. I have use @try { } @catch to Handel the exception and stop to crash from index 0 beyond bounds for empty array error but I want to implement some better way

@interface CategoryVC ()
{
    NSArray* GradientColour;

}

- (void)viewDidLoad {
    [super viewDidLoad];
     /*Gradient Colours*/
    GradientColour = @[CategoryEntertainmen2,CategoryGroceries2,CategoryAutomobile, CategoryClothing
                        , CategoryComputer,Categoryeducation,CategoryElectronics,CategoryEntertainment,CategoryGroceries,CategoryHealthButy,CategoryHome,CategoryResturant,CategoryToys,CategoryEntertainmen2,
        CategoryGroceries2,CategoryHealthButy2,CategoryHome2,CategoryResturant2,CategoryToys2,CategoryFlowers,CategoryBreakfast,
        CategorySpicyFood,CategoryFuriture 
                       ];


}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

      /*Gradient Colours*/
    if (indexPath.row <23)
    {
      [cell setImage:[UIImage imageNamed:@"Grass"] andColor:[ GradientColour  objectAtIndex:indexPath.row]];

    }else{
        @try {
            [cell setImage:[UIImage imageNamed:@"Grass"] andColor:[ GradientColour  objectAtIndex:indexPath.row-23]];
        } @catch (id theException) {
            /*Handell Crash Conditions*/
            [cell setImage:[UIImage imageNamed:@"Grass"] andColor:[ GradientColour  objectAtIndex:5]];
        }

    }

    return cell;
}

See more ..

samedi 30 mai 2015

How to smoothly allow the sending of messages in my chat app?

I have a chat application that uses Parse as a back-end. Let's say there's a conversation that looks something like this in the table so far:

I said: Hello

He said: Hey there

Now, if I want to type something in and click send, the table would go blank for a bit and then show all three messages. How can I achieve this affect in a much smoother way? For example, when I hit send, the message just pops under all the other messages without it going blank because it is refreshing the data and adding the new message.

When the send button is pressed, among other code, these two pieces of code run:

    self.messagesArray.append(messageObject)
    self.loadObjects()

The table is handled by a class that extends PFQueryTableViewController. Anyone have any ideas?

See more ..

display thumbnail images from URL’s in tableVeiw Cell

I want to display thumbnail images from URL’s in every tableView cell. it is working fine. But the problem is when I scroll is causes some GUI delays. I know it is because of URL request every time I scroll or every time new cell created. Is there any better way to do it, that does not cause any UI delays.

I'm using the following code:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: WelcomeCell = WelcomeCell();
    cell = self.tblViewStudent.dequeueReusableCellWithIdentifier("WelcomeCell") as WelcomeCell

    if news != nil {
    if news.count > 0 {
        var objNews = News();
        objNews = news.objectAtIndex(indexPath.row) as News;

        cell.lblNewsSubject.text = objNews.subject;
        cell.lblNewsTime.text = objNews.created_at;
        cell.lblNewsSummery.text = objNews.summery;

        let url = NSURL(string: objNews.thumbnailURL)
        let data = NSData(contentsOfURL: url!) 
        cell.viewImageThumbnail.image = UIImage(data: data!);
    } else {
        // do nothing
    }

    }
    return cell;

}

Thanks in advance.

See more ..

iOS - Swipeable UITableCells Without Constraints

I'm working on a project where I need to use 3 storyboards, one for iPhone 5, the other for iPhone 6, and the last for iPhone 6+. I need to implement Swipeable UITableCells to show more options in this project.

I followed this tutorial: http://ift.tt/1l7QCoP to semi-successfully get this done, but the problem is that this requires auto layout and manipulating constraints to make the table cells swipeable via a UIPanGestureRecognizer.

Is there any way to achieve the same user experience without using constraints? I'm kinda new to UIPanGestureRecognizer, so any advice on how to start on this would be wonderful, or if there are any tutorials out that that do the same things without using constraints.

See more ..

CUICatalog: Invalid asset name supplied: (null), or invalid scale factor: 1.000000

The above message appears while I try to load a table view from nib with custom cell in it. Note that I've already checked all the [UIImage imageNamed:] methods and everything is normal.

N.B: I'm using [self zoomRectForScrollView:zoomView withScale:scale withCenter:zoomView.center] for zooming an ImageView.

See more ..

Cells disappear when scroll down in my UITableView

when I scroll down in my TableView some contents of cell disappear (Labels and ImageViews). Please help me. I tried everything !!! My Code:

-(void)viewWillAppear:(BOOL)animated{
[comentarios removeAllObjects];
NSString *lookup=[NSString stringWithFormat:@"http://my.url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:lookup]];
[request setHTTPMethod:@"GET"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSMutableArray *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"%@",jsonDict);
for (int i=0; i<[jsonDict count]; i++) {
    Comentario *come=[[Comentario alloc] init];
    come.nick=[[jsonDict objectAtIndex:i] objectForKey:@"nick"];
    come.comment=[[jsonDict objectAtIndex:i] objectForKey:@"content"];
    come.avatar=[[jsonDict objectAtIndex:i] objectForKey:@"color"];
    [comentarios addObject:come];
}
[self reloadInputViews];
[self.comentariosTableView reloadData];
}

and

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell...
if( cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: CellIdentifier];
}

// Display recipe in the table cell
UIImageView *avatar = (UIImageView *)[cell viewWithTag:100];
avatar.image = [UIImage imageNamed:[[comentarios objectAtIndex:indexPath.row] avatar]];

UILabel *nick = (UILabel *)[cell viewWithTag:101];
nick.text =[[comentarios objectAtIndex:indexPath.row] nick];

UILabel *comment = (UILabel *)[cell viewWithTag:102];
comment.text = [[comentarios objectAtIndex:indexPath.row] comment];

UIButton *sinvoto = (UIButton *)[cell viewWithTag:103];

UIButton *ticket = (UIButton *)[cell viewWithTag:104];


return cell;
}

I can't see the mistake, please help me. Thank you in advance

See more ..

How do I display a cell in table view in a modal in iOS app

I have just started to learn coding on XCode for iOS app and am quite new to this environment.

I have a sale history table view controller that displays a list of orders that the cashier have entered from the previous menu.

In the list of orders page, each cells display the order id and summary of orders.

I want to be able to tap on each cell(order) and display the entire order in either a new page or preferably a popup on the same page modally.

However I am not sure which segue should I use and how do I go about doing that.

Can anyone assist on this topic?

Thank you!

See more ..

How to display content to cell using textLabel.text to a TableView object in Swift

I want to add a simple string to the textLabel.text property then display it in the cells in this example.

I added the number of sections, the number of rows in that section, and now trying to display data to the cells.

import UIKit

class ViewController: UIViewController, UITableViewDataSource {

// number of sections in table view
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

// number of rows in section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
}

// returns the content of each row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    // an object to represent each cell
    var cell = UITableViewCell()
    // configure
    cell.textLabel?.text? = "Hello"       - this is where i run into a problem
    //cell.textLabel?.text = "Hello"      - this is where i run into a problem
    return cell
}

See more ..

UITableView with dynamic cell size have wrong subviews width

There are a lot of similar questions about this subject at SO, but this is not a duplicate, I read literally all of them and still can't fix my issue. Looking for advice.

First. I have UITableView with dynamic row height. I'm using autolayout also. I have pretty simple layout:

UITableViewCell -> Content View -> UIView -> UILabel

My label have 6 constraints (width, height, left, top, bottom, right (all to UIView)). My UIView is a little bigger than UILabel and have same constraints but to it's superview - Content View.

I'm completely stuck with this: after scrolling, some of the rows randomly changes width of UIView (and label). I made a lot of attempts to fix it using different approach but didn't succeed. I won't tell what did I do, but I'll tell where I'm now.

I override my layoutSubviews method of UITableViewCell.

override func layoutSubviews() {

    super.layoutSubviews()

    contentView.layoutIfNeeded()

    let str : NSString = title.text! 
    let textSize = str.sizeWithAttributes([NSFontAttributeName: title.font])

    titleWidth.constant = textSize.width
    titleHeight.constant = textSize.height
    myViewWidth.constant = 30 + textSize.width // width and height constraints 
    myView.constant = 10 + textSize.height     // for UIView
}

After that, I'm getting this: row with wrong width look like this label is showed with full text as it must, but! UIView is smaller than UILabel, but it must be bigger.

What I do wrong? Ask any questions you'll have!

I also want to mention, that I have such behaviour only after deleting and inserting row to another section (in the same beginUpdates endUpdates block). Only after this I see such behaviour, but don't sure strictly.

See more ..

iOS8 UISearchController Covers Up UITableView

I've implemented a UISearchController for my tableview, with scopes and everything. However it doesn't display correctly when the view loads initially.

There are four different things I see depending on my actions.

This is what I see when the view first appears. I wouldn't expect the scope bar to appear:

http://ift.tt/1FLrazl

Now, if I click on the search bar, I see this:

http://ift.tt/1HVZdIq

Next, if I click on the Cancel button again, I see this on the table view:

  • Link in comments [1]

Finally, if I tap on the search bar again, I see what I would expect when I tapped on the search bar the first time:

  • Link in comments [2]

And if I cancel one more time, now the search bar displays correctly on the table view:

  • Link in comments [3]

Here's the relevant part of my TableViewController.

class BaseWineTableViewController: UITableViewController, UITableViewDelegate, UINavigationControllerDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate {

    var resultSearchController = UISearchController()

    func ConfigureSearchController() {
        self.resultSearchController = UISearchController(searchResultsController: nil)
        self.resultSearchController.searchResultsUpdater = self
        self.resultSearchController.searchBar.delegate = self
        self.resultSearchController.delegate = self

        self.resultSearchController.searchBar.showsCancelButton = true
        self.resultSearchController.searchBar.autocapitalizationType = .None
        self.resultSearchController.searchBar.showsScopeBar = true
        self.resultSearchController.searchBar.scopeButtonTitles = ["All", CELLAR_STATUSES.Cellared, CELLAR_STATUSES.Wishlist, CELLAR_STATUSES.Finished]

        self.resultSearchController.definesPresentationContext = true
        self.resultSearchController.dimsBackgroundDuringPresentation = false
        self.tableView.tableHeaderView = resultSearchController.searchBar
    }

See more ..

How to Animate Tableviewcells in a ScrollWheel fashion?, Swift

I am attempting to animate my tableview so that it looks like a scroll wheel when scrolling up and down. Similar to this picture.

Here is the code I've made to animate the tableview when scrolling. Unfortunately, it does not resemble a scroll wheel in the slightest. So my question is, what changes do I need to make to get my desired result? Do I need to rewrite it completely? I assume I do not need SpriteKit for this?

       //setup the CATransform3D Structure
    var rotation:CATransform3D = CATransform3DMakeRotation(CGFloat((90.0*M_PI)/180), CGFloat(0.0), CGFloat(0.7), CGFloat(0.4))
    rotation.m34 = (1.0/(-600))

    //Define the initial state
    cell.layer.shadowColor = UIColor.blackColor().CGColor
    cell.layer.shadowOffset = CGSizeMake(10, 10)
    cell.alpha = 0

    cell.layer.transform = rotation
    cell.layer.anchorPoint = CGPointMake(0, 0.5)

    //!!!FIX for issue #1 Cell position wrong------------
    if(cell.layer.position.x != 0)
    {
        cell.layer.position = CGPointMake(0, cell.layer.position.y);
    }

    //Defines the final state after the animation
    UIView.animateWithDuration(0.8, animations: {
        cell.layer.transform = CATransform3DIdentity
        cell.alpha = 1
        cell.layer.shadowOffset = CGSizeMake(0, 0)
    }, completion: nil)

See more ..

Updating PFObject in one cell affects other cells?

I am new to iOS. I have a UITableViewCell and UITableViewController. I have a like button within each cell. If it is pressed it changes color, which already works. I have it also updating a PFObject when it is pressed, specifically the likeCount. I don't know whether my problem is in the TableViewCell code or the TableViewController, but when I click the like button of one cell, it updates that cell AND another random cell. And whenever I scroll, it changes the location of the like...

Here is the code:

class ChinTwoTimelineTableViewController: UITableViewController {

var timelineData:NSMutableArray = NSMutableArray()

var likeCheck = false
var likeTotal = 0

func loadData() {
    timelineData.removeAllObjects()

    var findTimelineData:PFQuery = PFQuery(className: "ChinTwos")


    findTimelineData.findObjectsInBackgroundWithBlock{
        (objects:[AnyObject]?, error:NSError?)->Void in

        if let objects = findTimelineData.findObjects() as? [PFObject] {

            if error == nil{
                for object in objects{
                    let chinTwo:PFObject = object as PFObject
                    self.timelineData.addObject(chinTwo)
                }

                let array:NSArray = self.timelineData.reverseObjectEnumerator().allObjects
                self.timelineData = NSMutableArray(array: array)

                self.tableView.reloadData()

            }
        }
    }
}

override func viewDidLoad() {

    self.title = "Title"

    super.viewDidLoad()

    self.loadData()

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell:ChinTwoTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ChinTwoTableViewCell

    // Configure the cell...

    let chinTwo:PFObject = self.timelineData.objectAtIndex(indexPath.row) as! PFObject


    var myVar:Int = chinTwo.objectForKey("likeCount") as! Int
    cell.countLabel.text = String(myVar)

    cell.nameLabel.text = chinTwo.objectForKey("name") as? String
    cell.bodyText.text = chinTwo.objectForKey("body") as! String

    cell.bodyText.font = UIFont(name: "HelveticaNeue-UltraLight", size: 18)
    cell.bodyText.textAlignment = .Center

    return cell
}

@IBAction func likeButtonTapped(sender: AnyObject) {

        if likeCheck == false {

            println("1")
            var senderPoint = sender.convertPoint(sender.bounds.origin, toView: self.tableView)
            var indexPath = self.tableView.indexPathForRowAtPoint(senderPoint)
            let chinTwo:PFObject = self.timelineData.objectAtIndex(indexPath!.row) as! PFObject
            chinTwo["likeCount"] = (chinTwo["likeCount"] as! Int) + 1
            likeCheck = true
            likeTotal + likeTotal + 1

            chinUp.saveInBackgroundWithBlock {
                (success: Bool, error: NSError?) -> Void in
                if (success) {
                    println("Worked")
                } else {
                    println("Didn't Work")
                }
            }
            self.tableView.reloadData()


        } else {
            println("4 ")
            var senderPoint = sender.convertPoint(sender.bounds.origin, toView: self.tableView)
            var indexPath = self.tableView.indexPathForRowAtPoint(senderPoint)
            let chinTwo:PFObject = self.timelineData.objectAtIndex(indexPath!.row) as! PFObject
            chinTwo["likeCount"] = (chinTwo["likeCount"] as! Int) - 1
            likeCheck = false
            likeTotal = likeTotal - 1

            chinTwo.saveInBackgroundWithBlock {
                (success: Bool, error: NSError?) -> Void in
                if (success) {
                    println("Worked")
                } else {
                    println("Didn't Work")
                }
            }

            self.tableView.reloadData()


    }
}

Additionally, I am trying to figure out this check at the end... in terms of adding or decrementing the like count. I posted that here: Access variable from UITableViewCell in the TableViewController for specific cells?

Thank you for your help.

See more ..

Display selected CoreData value from UITableView in UITextView

I've got a TableViewController wich fetches the CoreData. Furthermore if I click on a cell it segues to the DetailViewController. But I don't know how I can display the Value in a UITextView of the selected row in said DetailViewController.

AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
_managedObjectContext  = delegate.managedObjectContext;

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"Note"];
_fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext sectionNameKeyPath:nil cacheName:nil];

[_fetchedResultsController setDelegate:self];
NSError *error = nil;
[_fetchedResultsController performFetch:&error];
if (error) {
    NSLog(@"Unable to perform Fetch");
    NSLog(@"%@, %@", error, error.localizedDescription);


    NSArray *objects = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];

How can i display the value and how do i ensure that the displayed value is the one wich i did select in the TableViewController?

See more ..

UICollectionView inside Static TableViewCell

I've seen many tutorials online pertaining to embedding UICollectionViews inside dynamic table view cells and subclassing the collection view to set the delegate but I was wondering if the process is any different for static table view cells.

I tried following the example here but I couldn't quite follow it through because it seems overly complicated with little to no explanation. Would anyone mind outlining the basic steps I need to go through with in order to get my collection view to work?

Many thanks!

See more ..

Access variable from UITableViewCell in the TableViewController for specific cells?

I am new to coding iOS. I have a TableViewCell which has a boolean in it (to check if my like button has been pressed).

class ChinTwoTableViewCell: UITableViewCell {

@IBOutlet var countLabel: UILabel!
@IBOutlet var nameLabel: UILabel!
@IBOutlet var bodyText: UITextView!

var likeCheck:Bool = false

// Other code

@IBAction func likeTapped(sender: AnyObject) {
    if((likeCheck) == false) {
        sender.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
        likeCheck = true
    } else {
        sender.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        likeCheck = false
    }
}    

}

I would like to access this boolean in my TableViewController, and then check if true, do stuff, if false, do stuff.

How can I check this so that it pertains to the correct row in the other class?

See more ..

ios/xcode/storyboard: How to adjust size of tableview in uiviewcontroller

I created a UIViewController and then placed a UITableView in it. Initially it let me resize the tableview, but now it no longer lets me do this. The tableview dimensions are not enabled (they show 600 x 600) and the handles do not appear on the edges of the tableview to drag in storyboard.

Can anyone suggest a fix to this. I have wasted 2 days on this problem.

I already have deleted the screens and recreated them multiple times and the same problem continues to happen.

The reason I want to make the tableview take up less than the whole screen is to have some buttons on the screen as well.

Thx.

See more ..

BackgroundImageView should Animate

I want to fade in an UIImageView as a BackgroundView of an UITableView. It's not animating. The image is just there. Any ideas why?

Here is my code:

override func viewWillAppear(animated: Bool)
{
    let backgroundImage = UIImage(named: "theImage")
    let imageView = UIImageView()
    imageView.image = backgroundImage
    imageView.contentMode = UIViewContentMode.ScaleAspectFit
    self.tableView.backgroundView = imageView

    //Tried it this way
    imageView.alpha = 0.0

    //and that way
    self.tableView.backgroundView?.alpha = 0.0

    UIView.animateWithDuration(3.0, animations: { () -> Void in
        //Both not animating
        self.tableView.backgroundView?.alpha = 1.0
        imageView.alpha = 1.0
    })
}

Thanks

See more ..

UITableView sort with NSSortDescriptor and UISegmentedControl doesn’t work

I want to sort my tableview by using a segmented control and sort it by a value from my datacore. According to Apple documentation my code below should work, but it doesn’t do anything.

Can anyone tell me what I am doing wrong?

- (void)viewDidLoad {
  [super viewDidLoad];

    UISegmentedControl *statFilter = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"A - Z", @"Stock", @"Price", nil]];
    [statFilter sizeToFit];
    [statFilter addTarget:self action:@selector(MySegmentControlAction:) forControlEvents: UIControlEventValueChanged];
    self.navigationItem.titleView = statFilter;

    self.artists = [[ArtistDataStore sharedStore] artists];
    [self.tableView reloadData];

    self.tableView.rowHeight = 60;

}


- (void)MySegmentControlAction:(UISegmentedControl *)segment
{
    NSArray *arrayToSort = [[ArtistDataStore sharedStore] artists];


    if(segment.selectedSegmentIndex == 0)
    {

        NSArray * result = [arrayToSort valueForKey:@"name"];

        NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
        result = [result sortedArrayUsingDescriptors:@[sd]];

    }
    if(segment.selectedSegmentIndex == 1)
    {
        NSArray * result = [arrayToSort valueForKey:@"stock"];

        NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
        result = [result sortedArrayUsingDescriptors:@[sd]];

    }
    if(segment.selectedSegmentIndex == 2)
    {
        NSArray * result = [arrayToSort valueForKey:@"price"];

        NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
        result = [result sortedArrayUsingDescriptors:@[sd]];

    }

    [self.tableView reloadData];
}

See more ..

Label text missing when scrolling in UITableView

I am getting this weird error when scrolling

enter image description here Label text missing

  
        let cell = tableView.dequeueReusableCellWithIdentifier("MessageCell", forIndexPath: indexPath) as! ChatTableNewViewCell

//setiing cell label text and other attributes
      
        return cell

This happens in both simulator and in iPad, moreover it doesn't happen always only when we scroll very fast or scroll couple of times. This is really annoying :(. Please help

See more ..

Parse - Get Image form Parse User Class in to UiTableView

I am experiment with parse.com and xcode 6. My question is: How can I load data from parse User Class in to a tableView. I don't want load only one image, it should doesn't matter how match.

See more ..

"static" UISearchBar extends it's margins to UITableView

I have a UISearchBar on my UITableView, here's the layout: enter image description here

Please note, I do not what UISearchBar to hide my UINavigationBar when searching!

When I start searching UISearchBar kind of extends it's margins to UITableView. Here's the preview of 2 states: enter image description here

Here's the video preview: http://ift.tt/1KE10Tg

The questions are: Why this happens and how to prevent this? Thanks.

See more ..

dequeueReusableCellWithIdentifier index out of bound

I'm having a UITableViewController which has a TableView in which I have a Cell which has another TableView in it.

When that internal TableView tries dequeueReusableCellWithIdentifier for indexPath (1,0) the app crashes with

Terminating app due to uncaught exception 'NSRangeException', 
reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

Although that internal TableView clearly has 3 sections. The stack trace being:

-[__NSArrayI objectAtIndex:] + 190
-[UITableViewDataSource tableView:indentationLevelForRowAtIndexPath:] + 61
-[UITableView _configureCellForDisplay:forIndexPath:]_block_invoke + 1711
+[UIView(Animation) performWithoutAnimation:] + 65
-[UITableView _configureCellForDisplay:forIndexPath:] + 312
-[UITableView dequeueReusableCellWithIdentifier:forIndexPath:] + 271

Because of the trace, I tried implementing

override func tableView(tableView: UITableView, 
              indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int {
  return 0
}

but then the app crashes at

-[UITableViewDataSource tableView:viewForFooterInSection:]

with the same index 1 beyond bounds [0 .. 0]...

See more ..

customize UITableView Header Section at run time

I have set header back ground using the code below but I want to change the color of header back again on run time when I click on the button that is added as a subview on the header. please provide me code, thanks in advance :)

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _tableView.bounds.size.width, 50)];

header.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"homeCellHeaderBackGround.png"]];

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 30)];
label.text = _array[section][@"name"];
label.textColor = [UIColor whiteColor];


[header addSubview:label];


UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(230, 10, 70, 35)];
[button addTarget:self action:@selector(onExpandButton:) forControlEvents:UIControlEventTouchUpInside];
//[button setTitle:@"Expand" forState:UIControlStateNormal];
[button setTag:section];

[header addSubview:button];

return header;

}

See more ..

tableview first 10 cell again regenrate after scrolling

I am using table view using custom coading with tag method to save memory. i was sucessful to show data in the view but the problem is hear -" like in the view if 10 cells are showing then if i scroll down like for one cell then it should show 2-11 cell data but it switches to 1-10 again.

hello, I am using table view using custom coading with tag method to save memory. i was sucessful to show data in the view but the problem is hear -" like in the view if 10 cells are showing then if i scroll down then these 10 cells with save data drom 1to10 show again.


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *cellIdentifier = @"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                         cellIdentifier];
UILabel *cellNAMElabl = nil;
UILabel *cellDetaillabl = nil;
UIImageView *imgView = nil;

if (cell == nil) {
    cell = [[UITableViewCell alloc]initWithStyle:
            UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];

    cellNAMElabl = [[UILabel alloc] initWithFrame:CGRectMake(88, 10, 150,        20)];
    [cellNAMElabl setTag:1];
    cellNAMElabl.text = [name5 objectAtIndex:indexPath.row];
    UIFont *myFont1 = [ UIFont fontWithName: @"Arial" size: 20.0 ];
    cellNAMElabl.font  = myFont1;
    [cell.contentView addSubview:cellNAMElabl];


    cellDetaillabl = [[UILabel alloc] initWithFrame:CGRectMake(88, 28, 150, 20)];
    [cellDetaillabl setTag:2];
    cellDetaillabl.text = [email5 objectAtIndex:indexPath.row];
    UIFont *myFont = [ UIFont fontWithName: @"Arial" size: 13.0 ];
    cellDetaillabl.font  = myFont;
    [cell.contentView addSubview:cellDetaillabl];


    imgView=[[UIImageView alloc] initWithFrame:CGRectMake(25, 5, 52, 50)];
    [imgView setTag:3];

    imgView.image = [imagepath5 objectAtIndex:indexPath.row];
                 [cell.contentView addSubview:imgView]; }
cellNAMElabl = (UILabel *)[cell viewWithTag:1];
cellDetaillabl = (UILabel*)[cell viewWithTag:2];
imgView = (UIImageView*)[cell viewWithTag:3];    

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

return cell;}

See more ..

Number formatting issue objective c

I have the following lines of code

distanceLabel = @"%.fmetres as the crow flies";
formattedNumber  = [NSString stringWithFormat:@"%.f", [s.distance doubleValue]];
cell.detailTextLabel.text = [NSString stringWithFormat:distanceLabel,formattedNumber];

Where formattedNumber = 376 after the 2nd line of code is executed, however cell.detailTextLabel.text = @"0metres as the crow flies"

Am I missing something obvious here? What is really throwing me off here is that if I refresh the table the cell.detailTextLabel.text = @"376metres as the crow flies"

See more ..

Tableview scroll makes issue on cells

I have a programatically created tableview

var tableView: UITableView  =   UITableView()
var items = ["1","2","3","4","5","6"," 1","L 2","La 3","La 4","La 5","La 6","L 7","La 8","La 9","La 10","La 11","Lab 12","Lab 13","Lab 14","Lab 15","Lab 16","Lab 17","Lab 18","Lab 19","Lab 20","La 1","L 2","La 3"]

   override func viewDidLoad() {
    super.viewDidLoad()
    tableView.frame         = CGRectMake(0, 50, self.view.frame.width,100);  //If we give self.view.frame.height It worked because no need to scroll
    tableView.delegate      = self
    tableView.dataSource  =  self
    tableView.estimatedRowHeight = 30
   tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")

    self.view.addSubview(tableView)
    }

Here is the code which have problem

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


    var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell

        if indexPath.row == 2 || indexPath.row == 3 {

            var redBtn = UIButton()
            redBtn = UIButton(frame: CGRectMake(0, 0, 40, 40))
            redBtn.backgroundColor = UIColor.redColor()
            redBtn.setTitle("das", forState: UIControlState.Normal)


            cell.contentView.addSubview(redBtn)



        }else {



        cell.textLabel?.textAlignment = NSTextAlignment.Center
        cell.textLabel?.text = items[indexPath.row]

      }
      return cell

        }

In the 2 nd and 3 rd row only i need to display the button.But when scroll the tableview it displays in all the cells.If increase the tableview height to view height then no problem becuase there is no scrolling happend.

I read this question UITableView scrolling and redraw issue from this i found it is because of reuse cell issue while scrolling.But that solution did not work for me.

Suitable solutions are welcome.I gave full code so you can copy and paste it to the project, and get the problem.

Thanks in Advance.

See more ..

UITableView inside UIScroll View Floating Header Issue

I implemented UITableView inside UIScrollView from this post: http://ift.tt/1K0qjh1

but I'm having issue with floating headers in my TableView. Is there any way to solve this?

See more ..

find user and add user with parse and get an error

I want my app to be able to add friend's username and show them in friend list view controller.My view will have username textfield for user to fill in order to search for friends and an add button to add them.
The process is that you type friend's username in the textfield and press add, it will search to see if that user's exist,if exist the app will automatically add that username and go to friend list view controller where I have to update friend list with the new one.I'm currently using parse.
Here's my code for adding user with parse in swift

@IBAction func addUser(sender: AnyObject) {
    var query = PFUser.query()
    var currentUser = PFUser.currentUser()
    query.whereKey("username", equalTo: usernameTextField) 
    query.getFirstObjectInBackgroundWithBlock{ (objects: PFObject!, error: NSError!) -> Void in 

        if error == nil {
            var friendList = PFUser.currentUser().relationForKey("friends")
            var addFriend = objects
            if addFriend != nil {
                PFRelation.addObject(addFriend)
                println("added")
            }
            PFUser.currentUser().saveInBackgroundWithBlock{
                (succeeded: Bool!, error: NSError!) in

                if error != nil {
                    println("Error")
                }
                else {
                    println("saved")
                }
            }
        }

    }
}

My app shows error 'PFObject' is not convertible to 'PFRelation'
This is the code that I've found in stackoverflow and tried

@IBAction func addUser(sender: AnyObject) {
    var query = PFUser.query()
    var now = PFUser.currentUser()
    query.whereKey("username", equalTo: usernameTextField) // use Breakpoint at this point and ok
    query.getFirstObjectInBackgroundWithBlock {          // <- use Breakpoint at this point and my app crash
        (object: PFObject!, error: NSError!) -> Void in
        if object == nil {
            NSLog("The getFirstObject request failed.")
            //add alertView here later

        } else {
            // The find succeeded.
            NSLog("Successfully retrieved the object.")
            //This can find username successfully
        }
        var friendsRelation : PFRelation = now.relationForKey("friendsRelation")
        friendsRelation.addObject(object)
    }
}

I've tried solutions that I've found in stack overflow and other sites but I still can't get it to work, I've tried 'for user in users (users is equal to my object)' loop but it didn't work and I'm stuck and I don't know if my code is all wrong. Did I miss some concept here? If so how do you write a code to add username and show them in friendlist view controller,I don't know what to do now.
I would greatly appreciate any help you can give me and let me know if you need any additional information (By the way my app will not link to Facebook at anyway).
Thank you!

See more ..

Grouping in TableView

There is an array of objects:

@property (strong, nonatomic) NSMutableArray *zArray;

Each object has field @property int category and can vary from 1 to 23 inclusive.

How can I create a TableView, so grouping it was on this field?

See more ..

vendredi 29 mai 2015

Crash when I re-enter a TableViewController due to an attempt to write to what I think is a mutable dictionary

I have the following nested mutable dictionary which I create and save into NSUSerDefaults

self.configDict is {
    objectsDict =     {
        "40E1507D" =         {
            lastUpdate = "2015-05-30 05:02:40 +0000";
            subObjects =             {
                "D84EA15E" =                 {
                    lastUpdate = "2015-05-30 05:02:40 +0000";
                    show = 1;
                    title = subObjectOne;
                };
                "F20047D4" =                 {
                    lastUpdate = "2015-05-30 05:02:40 +0000";
                    show = 1;
                    title = GreenObject;
                };
            };
            title = Default;
        };
        "9EE82B8F" =         {
            lastUpdate = "2015-05-30 05:02:40 +0000";
            subObjects =             {
                "AEF3F442" =                 {
                    lastUpdate = "2015-05-30 05:02:40 +0000";
                    show = 1;
                    title = YellowObject;
                };
            };
            title = Other;
        };
    };
    lastUpdate = "2015-05-30 05:02:40 +0000";
    showAllObjects = 1;
}

In my table view controller, when I first enter it (viewDidLoad), I load up NSUserDefaults as such

self.configDict = [[defaults objectForKey:@"Config"] mutableCopy];

In my .h, I have the dict defined as follows:

@property (strong, nonatomic) NSMutableDictionary *configDict;

I then proceed to update some fields in there say the lastUpdate time:

NSMutableDictionary *subObjectDict = objectsDict[@"40E1507D"][@"subObjects"][@"D84EA15E"];
subObjectDict[@"lastUpdate"] = [NSDate date];

This all works well, and I wrap things up with

[[NSUserDefaults standardUserDefaults] synchronize];

The crash happens when I exit the table view controller and re-enter it. The above code re-executes as described above, but as soon as I hit the statement:

subObjectDict[@"lastUpdate"] = [NSDate date];

It crashes with the following error: 2015-05-29 22:53:30.029 myApp[12837:128350] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object' * First throw call stack:

Is it because I have nested dictionaries and the mutable copy is not performing a deep copy? Why would it work the first time when I read the dictionary from NSUserDefaults, but when I re-enter the TVC it crashes.

See more ..

How to add button on a particular cell in tableview in swift

The ttile shows my question.I want to add button on 2 nd and 5 th cell only.And How can i do this?

Thanks in Advance.

See more ..

Separating lines disappear when I choose adjacent cells

I have a code as following ( I have omitted the unnecessary parts):

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject) -> PFTableViewCell? {

            var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as PFTableViewCell!
            if cell == nil {
                cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
            }
            self.tableView.allowsMultipleSelection = true
            self.tableView.separatorColor = UIColor.blueColor()
            self.tableView.tableFooterView = UIView(frame:CGRectZero) 
return cell
}

When I choose adjacent cells, the separating line between them disappears which is not what I want. Is it possible to avoid this? Thanks in advance for your help.

See more ..

Swift: How to connect table view controller to table view?

I have a custom UITableViewController that I'd like to control the table views of two view controllers. The first view controller will only have a table view that comprises half the view, while the second will comprise the entire view. I have the UITableViewController set up, but am struggling to connect the other table views to the controller.

As I'm new to Swift (and programming), I'd appreciate a solution. Essentially, now that I have the controller, how do I use it?

See more ..

I downcasted my variable but I cannot call the function of the new class

I created a few prototype cells in my iOS Swift project, and I am now trying to initialize the cells depending on how the form uses the cells.

Here's what the cells look like:

enter image description here

I am now attempting to create the form such that it starts with two disclosure cells (the cell that has "Detail >" on the right), followed by one with a switch.

Each of these prototypes are linked to their own individual classes.

Here's how I generate the cells:

var cell : UITableViewCell?
    switch indexPath.section {
    case 0:
        switch indexPath.row {
        case 0,1:
            cell = tableView.dequeueReusableCellWithIdentifier("reportCellWithDisclosureIndicator", forIndexPath: indexPath) as! reportCellWithDisclosureIndicator
        case 2:
            cell = tableView.dequeueReusableCellWithIdentifier("reportCellWithSwitch", forIndexPath: indexPath) as! reportCellWithSwitch
        default:
            cell = tableView.dequeueReusableCellWithIdentifier("reportCellWithDisclosureIndicator", forIndexPath: indexPath) as! reportCellWithDisclosureIndicator
        }
    default:
        cell = tableView.dequeueReusableCellWithIdentifier("reportCellWithDisclosureIndicator", forIndexPath: indexPath) as! reportCellWithDisclosureIndicator
    }

...

if(cell is reportCellWithSwitch) {
   cell?.configure("Smoking")
}

The function configure is a member of the reportCellWithSwitch class. The problem I have is when I try to configure that specific cell.

How can I use the configure function?

Do I have to declare specific individual variables per cell type?

Should I write a general class that holds all of my configurations and call the functions as needed?

Any ideas and insights would be very appreciated. Thanks!

See more ..

Getting tableView without its empty cell

I need to get tableView like VC.view

I create TVC in nib. And instantiate it with

CustomTableViewController *customTableViewController = [[CustomTableViewController alloc] initWithNibName:@"CustomTableViewController" bundle:nil];

Then I want to add it to my custom alert with code

 alertView.contentView = customTableViewController.view;

And it works. But....

Difficulties is here.

I have 5 rows in table view with different cell height. And then I add it to other view I have all height of VC.

How can I get tableView without its empty cells or its background? Setting BG color to clear does not helps

I know problem is here because then I create VC with nib, tableView did not setted, but then I already add it to the view - its sets with all its height

See more ..

Enable / disable button when row is tapped

I would like to enable my button for segue if minimum one row in tableView is selected. Also the button should be disabled if no row is selected / marked.

At the moment I have this code and Im only able to enable it but I can not disable it anymore:

`override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    var whatIsSelected: String = ""

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow()
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!

    whatIsSelected = currentCell.textLabel!.text!

    // Unmark selected
    if (currentCell.accessoryType == UITableViewCellAccessoryType.Checkmark) {
        currentCell.accessoryType = UITableViewCellAccessoryType.None
    // Mark selected category
    } else {
        currentCell.accessoryType = UITableViewCellAccessoryType.Checkmark
    }`

Thank you

See more ..

I have been trying for the longest while now to display an Array of dictionaries from a plist into a TableView. This is a snippet of the .plist file.

<array>
<dict>
    <key>dexNumber</key>
    <integer>1</integer>
    <key>formOrder</key>
    <integer>1</integer>
    <key>iconFilename</key>
    <string>pokemon-icon-1.png</string>
    <key>name</key>
    <string>Bulbasaur</string>
    <key>yield</key>
    <dict>
        <key>attack</key>
        <integer>0</integer>
        <key>defense</key>
        <integer>0</integer>
        <key>hp</key>
        <integer>0</integer>
        <key>spAttack</key>
        <integer>1</integer>
        <key>spDefense</key>
        <integer>0</integer>
        <key>speed</key>
        <integer>0</integer>
    </dict>
</dict>
<dict>
    <key>dexNumber</key>

The code never gets to (return self.data.count), as it always returns Unexpected nil while unwrapping optional on this third line.

if let path = NSBundle.mainBundle().pathForResource("dex", ofType: "plist"){
        if let dict = NSDictionary(contentsOfFile: path){
                data = dict.objectForKey("name") as! [String]
            }
    }

Changing (let dict = NSDictionary) to (let dict = NSArray) lets me print out the data on the console using println, but it does not let my display any data on the tableview. In addition, that method only allows me to view 1 array with all of its keys, instead of viewing all dictionary objects of one key.

Any instance of trying to view the file as NSDictionary always returns nil. Any instance of returning as NSArray gives a result that can't be displayed on the tableview, but can be displayed on the console using println. This code snippet is an example of code that prints a result.

let resultDictionary = NSArray(contentsOfFile: path)
    println("Loaded dex.plist file is --> \(resultDictionary?.description)")
    var myDict = NSArray(contentsOfFile: path)
    if let dict = myDict {
        //loading values
        Item0ID = dict.objectAtIndex(0)
        print(Item0ID)
    } else {
        println("WARNING: Couldn't create dictionary from dex.plist! Default values will be used!")
    }

This is what returns on the console

Optional("(\n {\n dexNumber = 1;\n formOrder = 1;\n iconFilename = \"pokemon-icon-1.png\";\n name = Bulbasaur;\n yield = {\n attack = 0;\n defense = 0;\n hp = 0;\n spAttack = 1;\n spDefense = 0;\n speed = 0;\n };\n },\n {\n dexNumber = 2;\n

How do I get my view to display a list as text labels and such on the tableview as opposed to nothing at all?

See more ..

Add segue to dynamically created cells

I am dynamically creating 9 cells that will fit into a UICollectionView. When tapped, each button will load a different view controller. As the cells are generated by data from an array, so I do not have the ability to set a segue with an identifier in Interface Builder.

I have been using this method: self.navigationController?.pushViewController(vc, animated: true), but I believe that it is not the most up-to-date way to transition to a different view controller.

The Questions:

  • Should I create a segue for each dynamic cell programically, if so: how?
  • Should I connect the one button in interface builder to a dummy view controller and switch out the destination view controller before the segue begins, if so: how would I switch out the destination view controller?

Interface Builder screenshot of setup:

Interface Builder Setup

See more ..

How can I populate a tableView with an NSSet? (swift)

I have a Person Class in tableView1, then in TableView2, the user adds brands to associate with the person. My fetch request is trying to get back the person they selected and populate the tableView's rows with the associated brands of that person, but I'm stuck here:

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.CellReuseIdentifier, forIndexPath: indexPath) as! UITableViewCell

        let brandSetAllObjects = brandSet?.allObjects


        let brand = brandSetAllObjects as? Brand[indexPath.row]
        cell.textLabel!.text = brand.valueForKey("name") as? String


        return cell
    }

Fetch:

 //Helper Function to Fetch Core Data
    func fetchCoreData() {
        //1
        let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate

        let managedContext = appDelegate.managedObjectContext!

        //2
        let fetchRequest = NSFetchRequest(entityName:"Person")


        //3
        var error: NSError?

        let fetchedResults =
        managedContext.executeFetchRequest(fetchRequest,
            error: &error) as? [NSManagedObject]

        if let results = fetchedResults as? [Person] {
            for selectedPerson in results {
                brandSet = selectedPerson.brands
                println(brandSet)
            }

        } else {
            println("Could not fetch \(error), \(error!.userInfo)")
        }

classes:

import Foundation
import CoreData

class Brand: NSManagedObject {

    @NSManaged var name: String
    @NSManaged var people: NSSet


}

import Foundation
import CoreData

class Person: NSManagedObject {

    @NSManaged var name: String
    @NSManaged var brands: NSSet

    func addBrandsObject(value: Brand) {
        self.mutableSetValueForKey("brands").addObject(value)
    }

}

See more ..

MvxTableViewCell not disposed

I have a memory leaks issue.

I basically have a MvxTableViewController databound to a observablecollection. I create a MvxTableViewController and add it to my Controller as a child and I add the view as a subviews.

Problem is, the Cell in the table never gets disposed, leaking memory.

// When the view gets removed from the stack, the cells disposed method is never called and I can see the memory not going away, using the Xcode Instruments tool.  The table dispose gets called as expected. but not the cell
public partial class ParticipantTableViewCell : MvxTableViewCell
{
    readonly UILabel _nameLabel = new UILabel();
    readonly UILabel _locationLabel = new UILabel();
    readonly PictureContainer _pictureView = new PictureContainer(7.0f);

    public ParticipantTableViewCell (IntPtr handle) : base(handle)
    {
        BackgroundColor = UIColor.Clear;
        SelectionStyle = UITableViewCellSelectionStyle.None;

        ContentView.AddSubviews(new UIView[] {_nameLabel, _locationLabel, _pictureView});
        _pictureView.TransparentBackground = true;

        SetupConstraints();

        // Since this view is readonly, I've removed the actual binding code
        // and instead manually init each views.
        this.DelayBind(() => {
            _nameLabel.Text = ((ParticipantViewModel)DataContext).Name;
            _locationLabel.Text = ((ParticipantViewModel)DataContext).Location;
            IsSelected = ((ParticipantViewModel)DataContext).IsSelected;
            _pictureView.AvatarImage.Image = UIImage.FromFile ("Media/" + ((ParticipantViewModel)DataContext).AvatarUrl);
        });
    }

    void SetupConstraints ()
    {
        ContentView.Subviews.ForEach(v => v.TranslatesAutoresizingMaskIntoConstraints = false);

        ContentView.AddConstraints(
            _pictureView.Height().EqualTo().HeightOf(ContentView),
            _pictureView.Width().EqualTo().HeightOf(ContentView),
            _pictureView.WithSameCenterY(ContentView),
            _pictureView.Left().EqualTo(6.0f).LeftOf(ContentView),

            _nameLabel.Left().EqualTo(10.0f).RightOf(_pictureView),
            _nameLabel.Right().EqualTo().RightOf(ContentView),
            _nameLabel.Bottom().EqualTo(2.0f).CenterYOf(ContentView),

            _locationLabel.Left().EqualTo(10.0f).RightOf(_pictureView),
            _locationLabel.Right().EqualTo().RightOf(ContentView),
            _locationLabel.Top().EqualTo(4.0f).CenterYOf(ContentView)

        );
    }

    // never called
    protected override void Dispose (bool disposing)
    {
        base.Dispose(disposing);
    }

}

    class FriendsView : MvxTableViewController
{
    protected new FriendsViewModel ViewModel { get { return (FriendsViewModel) base.ViewModel; } }

    public FriendsView ()
    {
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad();
        TableView.BackgroundColor = UIColor.Clear;
        TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
        TableView.RowHeight = 60;
        TableView.ScrollEnabled = false;

        var source = new MvxSimpleTableViewSource(TableView, typeof(ParticipantTableViewCell));
        TableView.Source = source;

        var set = this.CreateBindingSet<FriendsView, FriendsViewModel>();
        set.Bind(source).To(vm => vm.YuFitFriends);
        set.Apply();
    }
}

Anybody got an idea as to why my cells are leaking ?

thanks pat

See more ..

iOS Messages App UITableViewCell Insert Animation

What I am wondering is how I can go about achieving an animation like the iOS Messages app animation whenever YOU send a message. The animation takes the text from the text field inside inputaccessoryview and animates to the uitableviewcell.

See more ..

Prevent keyboard dismissal on UITableView cell touch

I have a UITableView with several rows with buttons inside. The same page contains UITextField control. Once I activated the TextField input I want to keep it active even if I press the button within a cell within UITableView.

Right now any touch on UITableView dismiss my keyboard and doesn't trigger UITouchUpInside. I tried to disable Cancellable content touch but it didn't help.

See more ..

UITableViewController - TableView wider than screen

I'm having some problem my whole day. I'm using UITableViewController. TableView has 5 static cells. I put a label inside my cell and gave it constraints. This is my cell: Cell

Every time when I change the screen to different version of iPhone, it gives me warning that width of this label is 600 (default in storyboard) and it goes of the screen on the right side. Why TableViewController is not setting TableView screen size? What am I missing here? Is this actually a subview of viewController and if so, how to tell proper size of tableView inside storyboard with constraints?

See more ..

UItableview cell's height increases dynamically depending on the amount of content in it

I need a UITableview which has cell of dynamic height . The height increases when the size of text in it increases . Thank you guyz

See more ..

Tableview reload with setNeedsDisplay not working

I have a tableview in a view that lists all the steps that will be executed. I want to show a step as marked when the step was executed. The problem I am facing is that the tableview does not refresh until the procedure executed all the steps. Consequently all the steps show as marked at the same time.

This is my function which starts running when the user presses a button:

-(void)Initialiseer {
    //do something for the first step
    [self.MyTableView reloadData];
    [self.MyView setNeedsDisplay];

    //do something for the second step
    [self.MyTableView reloadData];
    [self.MyView setNeedsDisplay];

    //do something for the third step
    [self.MyTableView reloadData];
    [self.MyView setNeedsDisplay];
}

MyView is the view IBOutlet. MyTableView is the tableview IBOutlet. I also tried [self.view setNeedsDisplay] and [self. MyTableView setNeedsDisplay] but that does not work either. I also tried getting the cell from the tableview and making the changes on the cell itself. Nothing is refreshed until the procedure finished executing completely...

Can someone tell me what I am doing wrong? I am new to iOS development and I searched, read, tried... but did not find an answer so far.

See more ..

tableView cellForRowAtIndexPath method not getting called

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:   NSIndexPath) -> UITableViewCell {
    print("WTF is this getting hit...")

    let Cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell

    Cell.textLabel?.text = self.funlists[indexPath.row]

    print("This better be getting hit")


    return Cell;
}

for some reason this method isn't getting called.

See more ..

Dynamic Height Issue for UITableView Cells (Swift)

Dynamic text of variable length are being injected into tableview cell labels. In order for the tableview cells' height to be dynamically sized, I have implemented in viewDidLoad():

self.tableView.estimatedRowHeight = 88.0
self.tableView.rowHeight = UITableViewAutomaticDimension

This works nicely for the cells that have yet to be scrolled to (as UITableViewAutomaticDimention is called upon scrolling to the cell) and all is well for those, but not for the cells that are initially rendered onscreen after loading the data.

I have tried reloading the data (as suggested in many other resources):

self.tableView.reloadData()

in both viewDidAppear() and viewWillAppear() and it was to no avail. I am lost.. does anyone know how to have xcode render the dynamic height for the cells loaded initially on screen? Alternatively, if there is a better method completely, please let me know!

See more ..