vendredi 8 mai 2015

iOS Add Label on TableCell at Indexpath

I'm trying to present a label every time the user double taps on my cell. I can detect the taps and I can execute code from them but I'm having an issue with the labels. For some reason the labels are being added two sometimes three cells below the one it should be added on. I need the label to be added on the cell that was tapped, shouldn't be to hard to do.

Here is my code, thanks in advance.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    static NSString *CellIdentifier = @"cell";

    Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (nil == cell)
    {
        cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    PFObject *tempObject = [_myArray objectAtIndex:indexPath.row];
    NSString *currentUser = [[PFUser currentUser]username];

    //NSLog(@"%@",tempObject);
    NSArray *test = [tempObject valueForKey:@"Like"];
    //NSLog(@"%lu",(unsigned long)test.count);


    NSTimeInterval now = [[[NSDate alloc] init] timeIntervalSince1970];
    if ((now - lastClick < 0.3) & [indexPath isEqual:lastIndexPath]) {

        //cell.test.hidden = NO;
        CGRect frame = CGRectMake(0,0, 80, 40);

        UILabel *label1 = [[UILabel alloc]init];

        label1.frame = frame;

        label1.text = @"first label";
        [cell.contentView addSubview:label1];


        if ([test containsObject:currentUser]) {
            NSLog(@"1");

            [tempObject removeObject:currentUser forKey:@"Like"];
            [tempObject saveInBackground];

        }else {
            NSLog(@"2");
            [tempObject addUniqueObject:currentUser forKey:@"Like"];
            [tempObject saveInBackground];
        }

    }

    lastClick = now;
    lastIndexPath = indexPath;

}

Translate computed property from Category into Swift Extension

I have the following objective-c category:

@implementation UINavigationBar (Awesome)
static char overlayKey;
static char emptyImageKey;

- (UIView *)overlay
{
    return objc_getAssociatedObject(self, &overlayKey);
}

- (void)setOverlay:(UIView *)overlay
{
    objc_setAssociatedObject(self, &overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end

I tried to translate it into a Swift extension like this:

var AssociatedObjectHandle: UInt8 = 0

extension UINavigationBar {

  var stringProperty:Character {
    get {
      return objc_getAssociatedObject(self, &AssociatedObjectHandle) as! Character
    }
  }


  func setOverlay(overlay: UIView) {
    objc_setAssociatedObject(self, &AssociatedObjectHandle, overlay, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))

  }

}

It looks strange because I created a global variable AssociatedObjectHandle and I am not sure what the Character actually does?

Is this the correct way to translate the computed property?

UILabel flicker when changing font dynamically on UITableViewCell

tableView.estimatedRowHeight = 90.0
tableView.rowHeight = UITableViewAutomaticDimension
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    //ask for a reusable cell from the tableview, the tableview will create a new one if it doesn't have any
    let cell = self.tableView.dequeueReusableCellWithIdentifier("DetailCell") as DetailCell

    var detail : Detail
    detail = Details[indexPath.row]

    var paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 15
    paragraphStyle.alignment = NSTextAlignment.Right

    var attrString = NSMutableAttributedString(string: detail.detailText)
    attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))

    var fontName = cell.myLabel.font.fontName

    cell.myLabel.font = UIFont(name:fontName, size: pointSize)
    cell.myLabel.attributedText = attrString


    return cell
}

pointSize changes as the user pinches (used UIPinchRecognizer) the default pointSize of myLabel is 17. The code works perfectly when pinched to increase or decrease the pointSize. But while scrolling first the default size is applied and then increased or decreased size due to this the cells are giving a flicker effect while scrolling.

How do I avoid this? Is there any sample example already done for UITableViewCells

Unable to get custom MKAnnotationView callout to appear

I'm building an OSX application that uses Mapkit, and I'm trying to get a callout to appear when I click on an MKAnnotationView on my map. To do this I'm implementing the MKMapViewDelegate, and the following function :

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[LocationPin class]]) {
    LocationPin *returnPin = (LocationPin *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"LocationPin"];
    if (!returnPin){
        returnPin = [LocationPin createLocationPinForMapView:mapView annotation:annotation];
    }
    returnPin.title = annotation.title;
    NSButton *rightButton = [[NSButton alloc] initWithFrame:NSMakeRect(0.0, 0.0, 100.0, 80.0)];
    [rightButton setTitle:@"Info"];
    [rightButton setBezelStyle:NSShadowlessSquareBezelStyle];
    returnPin.annotation = annotation;
    returnPin.canShowCallout = YES;
    returnPin.rightCalloutAccessoryView = rightButton;
    return returnPin;
    }
    return nil;
    }

The function runs fine everytime I put a new pin down, and I made sure the titles of the pins are not empty or null, but the callout still is not showing up. Anybody have any ideas?

EDIT: After looking through Anna's response, I realized I misunderstood how to implement the MKAnnotation protocol. I've deleted my LocationPin class, which inherited from MKAnnotationView, and instead added the following class to represent my custom MKAnnotation, with a class inside of it to generate a custom MKAnnotationView:

@implementation LocationAnnotation:

-(id)initWithTitle:(NSString *)newTitle Location:(CLLocationCoordinate2D)location     {
    self = [super init];

    if(self) {
    _title = newTitle;
    _coordinate = location;
    }

    return self;
}

- (MKAnnotationView *)annotationView {

    MKAnnotationView *annotationView = [[MKAnnotationView alloc]initWithAnnotation:self reuseIdentifier:@"LocAnno"];
    annotationView.enabled = YES;
    annotationView.canShowCallout = YES;
    annotationView.image = [NSImage imageNamed:@"dvd"];

    NSButton *rightButton = [[NSButton alloc] initWithFrame:NSMakeRect(0.0, 0.0, 100.0, 80.0)];
    [rightButton setTitle:@"Info"];
    [rightButton setBezelStyle:NSShadowlessSquareBezelStyle];

    annotationView.rightCalloutAccessoryView = rightButton;

    return annotationView;
}

@end

I've also changed the MKMapViewDelegate function the following way now:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[LocationAnnotation class]]) {

        LocationAnnotation *anno = (LocationAnnotation *)annotation;
        MKAnnotationView *returnPin = [mapView dequeueReusableAnnotationViewWithIdentifier:@"LocAnno"];
        if (!returnPin){
            returnPin = anno.annotationView;
        }
        else {
            returnPin.annotation = annotation;
        }
        return returnPin;
    }
    return nil;
}

But the callout still is not appearing. Any help is appreciated.

Edit 2: As requested, LocationAnnotation.h:

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface LocationAnnotation : NSObject <MKAnnotation>

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (copy, nonatomic) NSString *title;

-(id)initWithTitle:(NSString *)newTitle Location:(CLLocationCoordinate2D)location;
-(MKAnnotationView *)annotationView;



@end

Objective-C Refresh Table View (RSS/xCode)

I'm trying to implement a pull-to-refresh feature on my RSS feed table. The list pulls normally when loading the app, but I essentially need to replicate that for the pull-down.

Could anyone help as to why the code isn't working?

#import "RSSTableViewController.h"
#import "RSSDetailViewController.h"

@interface RSSTableViewController () {


    NSXMLParser *parser;
    NSMutableArray *feeds;
    NSMutableDictionary *item;
    NSMutableString *title;
    NSMutableString *link;
    NSString *element;

}

@end

@implementation RSSTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // RSS Settings
    feeds = [[NSMutableArray alloc] init];
    NSURL *url = [NSURL URLWithString:@"http://ift.tt/1AKPEEt"];
    //
    // BBC RSS - http://ift.tt/1Rjha6i
    //
    parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    [parser setDelegate:self];
    [parser setShouldResolveExternalEntities:NO];
    [parser parse];

    // Pull to Refresh
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [self.tableView addSubview:refreshControl];
    [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];

}


    //Refresh handler
- (void)refresh:(UIRefreshControl *)refreshControl {


    [self.rssTableView reloadData];
    [refreshControl endRefreshing];
}




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

#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 feeds.count;
}


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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.textLabel.text = [[feeds objectAtIndex:indexPath.row] objectForKey:@"title"];

    return cell;
}



- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

    element = elementName;

    if ([element isEqualToString:@"item"]) {

        item = [[NSMutableDictionary alloc]init];
        title = [[NSMutableString alloc]init];
        link = [[NSMutableString alloc]init];
    }


}



- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if ([elementName isEqualToString:@"item"]) {

        [item setObject:title forKey:@"title"];
        [item setObject:link forKey:@"link"];

        [feeds addObject:[item copy]];

    }

}



-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

    if ([element isEqualToString:@"title"]) {
        [title appendString:string];
    }
    else if ([element isEqualToString:@"link"]) {
        [link appendString:string];

    }

}


-(void)parserDidEndDocument:(NSXMLParser *)parser {

    [self.tableView reloadData];

}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        NSString *string = [feeds[indexPath.row] objectForKey:@"link"];
        [[segue destinationViewController] setUrl:string];

    }

}



@end

I'm really stuck here and need to know to move on! Please do help!

EXEC_BAD_ACCESS on dequeuing cell from UICollectionView

I have a problem when dequeuing a UICollectionView cell from the storyboard. I have a view controller with a collection view as one of the subviews. The VC is set as the collection view's data source and delegate. The collection view has a couple of prototype cells with identifiers set.

When doing this:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.sizingCell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"CellId" forIndexPath:nil];
}

I get an EXEC_BAD_ACCESS on the self.sizingCell line. Interestingly, when I created a new test project with a view controller containing a collection view and did the same thing in viewDidLoad, the collection view's cell was created with no issues. Did anyone else run into a similar issue?

Black bar over a TableView just above TabBar

I have a UITableView with cells which perform a segue to an other simple detail view. The UITableView and detail view are embed in a Navigation Controller.

On my UITableView I put a UISearchController bar folowing this tutorial: http://ift.tt/1dStQBT

So now, I have the following graphic problem: When I perform a segue by tapping a cell after having make a research, I arrive to my detail view. But when I tap the Back button in the Navigation Bar, a mysterious black bar appears just above the TabBar. When the animation is over, the black bar disappears.

enter image description here

But when I tap the return button from the detail view without having done a research to arrive at this detail view, there is no black bar.

I can't understand why there is that black bar. I just note the black bar's height is equal to the TabBar's height. Maybe a link ?