How to load URL on UITableViewCell touch - arrays

New at this, just trying to make a link load if a certain UITableView cell is touched.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSArray *deals = [dic objectForKey:#"deals"];
NSDictionary *dealOne = [deals objectAtIndex:0];
NSString *url = [dealOne objectForKey:#"url"];
UITouch *touch = [[event allTouches] anyObject];
if([touch isKindOfClass:[UITableViewCell class]])
{
UITableViewCell *cell;
CGPoint location = [touch locationInView: self.view];
cell.center = location;
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}
NSLog(#"TABLECELL TOUCHED");
}

Solved using the following. In this case, I wanted to have a link load when the cell was touched for "finalDealOne." When the cell is double-tapped, the link loads.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSArray *deals = [dic objectForKey:#"deals"];
NSDictionary *dealOne = [deals objectAtIndex:0];
NSString *title = [dealOne objectForKey:#"title"];
NSString *finalDealOne = [NSString stringWithFormat:#"Deal One:\n\n''%#''\n\nDouble tap here to redeem offer.",title];
(NSIndexPath *)indexPath
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(finalDealOne)];
tapped.numberOfTapsRequired = 2;
[cell addGestureRecognizer:tapped];
}
To make this work, I included the following reference:
- (void)finalDealOne
{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSArray *deals = [dic objectForKey:#"deals"];
NSDictionary *dealOne = [deals objectAtIndex:0];
NSString *url = [dealOne objectForKey:#"url"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

Related

Swift: Could not cast value of type '__NSCFNumber' to 'NSString'

I have this code:
let active: NSString = NSString.init()
for value in 0..<(array.count + 1){
let validateData: NSDictionary = array.object(at: value) as! NSDictionary
let key: NSString = validateData.object(forKey: "clave") as! NSString
let name: NSString = validateData.object(forKey: "nombre") as! NSString
active = validateData.object(forKey: "activo") as! NSString
let sucursal_ID: NSString = validateData.object(forKey: "id_sucursal") as! NSString
let sucursal_Name: NSString = validateData.object(forKey: "nombre_sucursal") as! NSString
if !(key.isEqual(to: "")){
NSLog("clave: %#", key)
NSLog("nombre: %#", name)
actives?.add(active)
names?.add(name)
keys?.add(key)
sucursalesID?.add(sucursal_ID)
if sucursal_Name != "" {
NSLog("Es bimbo")
sucursalesNames?.add(sucursal_Name)
}
}
}
I am getting the error:
Could not cast value of type '__NSFCNumber' to 'NSString' in line active = validateData.object(forKey: "activo") as! NSString ** Thread 1: signal SIGABRT **
Why is that happening? And what can I do to solve it

UITableCell Width Resizing on scroll

I have an issue with a UITableViewController where as soon as you scroll down the background image of the cell increases in size. All the images are set to a width of 320px but still after you scroll the cell background image expands.
Can anyone explain why this is happening and how to fix it?
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (jsonResults.count == 0)
{
return 1;
}
else
{
return [jsonResults count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UIImage *selectionBackground;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (jsonResults.count == 0)
{
cell.backgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"topAndBottomRow.png"]
stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];
selectionBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
[cell.selectedBackgroundView setBackgroundColor:[UIColor colorWithPatternImage:selectionBackground]];
cell.textLabel.text = #"Nothing was found :(";
cell.detailTextLabel.text = #"Click here to add a venue!";
//cell.textLabel.textColor= [UIColor colorWithRed:(79/255.0) green:(129/255.0) blue:(189/255.0) alpha:1] ;
cell.textLabel.font = [UIFont fontWithName:#"Berlin Sans FB" size:22];
cell.detailTextLabel.font = [UIFont fontWithName:#"Berlin Sans FB" size:14];
cell.backgroundColor = [UIColor clearColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
else
{
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
cell.userInteractionEnabled = YES;
NSDictionary *venuesdict = [jsonResults objectAtIndex:indexPath.row];
NSString *addresslineone = [venuesdict objectForKey:#"address1"];
NSString *postcode = [venuesdict objectForKey:#"postcode"];
NSInteger sectionRows = [tableView numberOfRowsInSection:[indexPath section]];
NSInteger row = [indexPath row];
if (row == 0 && row == sectionRows - 1)
{
//rowBackground = [UIImage imageNamed:#"topAndBottomRow.png"];
cell.backgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"topAndBottomRow.png"]
stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];
selectionBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
}
else if (row == 0)
{
//rowBackground = [UIImage imageNamed:#"topRow.png"];
cell.backgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"topRow.png"]
stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
selectionBackground = [UIImage imageNamed:#"topRowSelected.png"];
}
else if (row == sectionRows - 1)
{
//rowBackground = [UIImage imageNamed:#"bottomRow.png"];
cell.backgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"bottomRow.png"]
stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
//rowBackground = [UIImage imageNamed:#"bottomRow.png"];
selectionBackground = [UIImage imageNamed:#"bottomRowSelected.png"];
}
else
{
cell.backgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"middleRow.png"]
stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
//rowBackground = [UIImage imageNamed:#"middleRow.png"];
selectionBackground = [UIImage imageNamed:#"middleRowSelected.png"];
}
UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.selectedBackgroundView.frame];
[imgView setImage:selectionBackground];
[cell.selectedBackgroundView addSubview:imgView];
[cell.selectedBackgroundView setBackgroundColor:[UIColor colorWithPatternImage:selectionBackground]];
cell.textLabel.text = [venuesdict objectForKey:#"name"];
NSString *imagename = [venuesdict objectForKey:#"imagename"];
cell.imageView.image = [UIImage imageNamed:imagename];
cell.detailTextLabel.text = [NSString stringWithFormat:#" %#, %#",addresslineone,postcode];
cell.textLabel.font = [UIFont fontWithName:#"Berlin Sans FB" size:22];
cell.detailTextLabel.font = [UIFont fontWithName:#"Berlin Sans FB" size:10];
cell.backgroundColor = [UIColor clearColor];
NSString *version = [[UIDevice currentDevice] systemVersion];
BOOL isAtLeast7 = [version floatValue] >= 7.0;
if (!isAtLeast7 == YES)
{
cell.detailTextLabel.backgroundColor = [UIColor grayColor];
cell.textLabel.backgroundColor = [UIColor grayColor];
}
}
return cell;
}
Try to change this line
UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.selectedBackgroundView.frame];
into this
UIImageView *imgView = [[UIImageView alloc] initWithFrame:cell.selectedBackgroundView.bounds];

Using Autolayout to position UITextField next to UILabel

I would like to use auto layout to position a UITextField next to cell.textLabel when a UITableView goes into edit mode. The code that I have works correctly but I get a message in the log that says some existing constraints had to be broken.
UILabel *label = cell.textLabel;
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0.0, 0.0, 400.0, 22.0)];
textField.placeholder = cell.textLabel.text;
textField.translatesAutoresizingMaskIntoConstraints = NO;
textField.text = text;
[cell.contentView addSubview:textField];
[cell addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:[label]-[textField]-|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(label,textField)]];
[cell addConstraint:[NSLayoutConstraint constraintWithItem:textField attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:label attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
Log message is:
(
"<NSAutoresizingMaskLayoutConstraint:0x1066abc0 h=--& v=--& H:[UITableViewCellContentView:0x9a7d070(934)]>",
"<NSAutoresizingMaskLayoutConstraint:0x10660a90 h=--& v=--& H:[UILabel:0x9a93ef0(914)]>",
"<NSLayoutConstraint:0x1065ea60 H:[UITextField:0x1065c660]-(NSSpace(20))-| (Names: '|':UITableViewCellContentView:0x9a7d070 )>",
"<NSAutoresizingMaskLayoutConstraint:0x10660a50 h=--& v=--& UILabel:0x9a93ef0.midX == + 467>",
"<NSLayoutConstraint:0x10669280 H:[UILabel:0x9a93ef0]-(NSSpace(8))-[UITextField:0x1065c660]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x10669280 H:[UILabel:0x9a93ef0]-(NSSpace(8))-[UITextField:0x1065c660]>
I think that this is caused by conflicting restraints with the cell.textLabel width. So my question is if there is another way to have a textfield in a standard table view cell that stretches from the textLabel width to the end of the cell without breaking default constraints. I feel like I'm close but I can't quite get there. I've searched Google over for three weeks but can't quite get my head around this. I've also watched WWDC videos on auto layout (perhaps I'm just an idiot). Thanks for your help.
Instead of trying to manipulate Apple's standard cell, I took the plunge and wrote my own UITableViewCell subclass that mimics UITableViewCellStyleValue1. When the tableview goes into edit mode, in the simplest terms I hide the value label and display the textfield. For those who might be struggling with the same thing, I'm posting some code to help you get started:
#interface NXAlphaNumericTextFieldCell : UITableViewCell<UITextFieldDelegate,NumberKeyboardDelegate>
#property (strong, nonatomic) UITextField *inputTextField;
#property (strong, nonatomic) UILabel *titleLabel;
#property (strong, nonatomic) UILabel *valueLabel;
#property (strong, nonatomic) NSArray *xTitleLabelConstraints;
#property (strong, nonatomic) NSArray *xTextFieldConstraints;
#property (strong, nonatomic) NSArray *xValueLabelConstraints;
#end
And a few methods in the implementation:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
self.titleLabel.backgroundColor = [UIColor clearColor];
self.valueLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
self.valueLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.valueLabel.textColor = [UIColor colorWithRed:81.0/255.0 green:102.0/255.0 blue:145.0/255.0 alpha:1.0];
self.valueLabel.backgroundColor = [UIColor clearColor];
self.inputTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 100, 44.0f)];
self.inputTextField.translatesAutoresizingMaskIntoConstraints = NO;
self.inputTextField.autocapitalizationType = UITextAutocapitalizationTypeWords;
self.inputTextField.autocorrectionType = UITextAutocorrectionTypeYes;
self.inputTextField.clearButtonMode = UITextFieldViewModeAlways;
self.inputTextField.delegate = self;
[self.contentView addSubview:self.valueLabel];
[self.contentView addSubview:self.titleLabel];
[self.contentView addSubview:self.inputTextField];
UILabel *textLabel = self.titleLabel;
NSDictionary *labelTextFieldViewsDictionary = NSDictionaryOfVariableBindings(textLabel);
self.xTitleLabelConstraints = [NSLayoutConstraint constraintsWithVisualFormat:#"|-[textLabel]"
options:0
metrics:nil
views:labelTextFieldViewsDictionary];
UITextField *textfield = self.inputTextField;
labelTextFieldViewsDictionary = NSDictionaryOfVariableBindings(textLabel, textfield);
self.xTextFieldConstraints = [NSLayoutConstraint constraintsWithVisualFormat:#"|-[textLabel]-50-[textfield]-|"
options:0
metrics:nil
views:labelTextFieldViewsDictionary];
UILabel *valueLabel = self.valueLabel;
labelTextFieldViewsDictionary = NSDictionaryOfVariableBindings(valueLabel);
self.xValueLabelConstraints = [NSLayoutConstraint constraintsWithVisualFormat:#"H:[valueLabel]-|"
options:0
metrics:nil
views:labelTextFieldViewsDictionary];
[self setNeedsUpdateConstraints];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
if (self.isEditing) {
[self.inputTextField becomeFirstResponder];
}
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
[self addConstraints:self.xTitleLabelConstraints];
if (editing) {
if (self.inputType == kCellInputTypeAlphaNumeric) {
self.inputTextField.keyboardType = UIKeyboardTypeAlphabet;
} else if (self.inputType == kCellInputTypeEmail) {
self.inputTextField.keyboardType = UIKeyboardTypeEmailAddress;
} else if (self.inputType == kCellInputTypePhoneNumber) {
self.inputTextField.keyboardType = UIKeyboardTypeNamePhonePad;
} else {
if (!self.numberKeyboard) {
self.numberKeyboard = [[NumberKeyboard alloc] initWithNibName:#"NumberKeyboard" bundle:nil];
self.numberKeyboard.textField = self.inputTextField;
self.numberKeyboard.showsPeriod = YES;
self.numberKeyboard.delegate = self;
}
self.inputTextField.inputView = self.numberKeyboard.view;
}
self.inputTextField.text = self.valueLabel.text;
self.inputTextField.placeholder = self.titleLabel.text;
self.valueLabel.hidden = YES;
self.inputTextField.hidden = NO;
[self removeConstraints:self.xValueLabelConstraints];
[self addConstraints:self.xTextFieldConstraints];
} else {
[self.inputTextField resignFirstResponder];
self.inputTextField.hidden = YES;
self.valueLabel.hidden = NO;
[self removeConstraints:self.xTextFieldConstraints];
[self addConstraints:self.xValueLabelConstraints];
}
}
- (void)updateConstraints
{
[super updateConstraints];
if (self.editing) {
[self removeConstraints:self.xValueLabelConstraints];
[self addConstraints:self.xTextFieldConstraints];
} else {
[self removeConstraints:self.xTextFieldConstraints];
[self addConstraints:self.xValueLabelConstraints];
}
}

Search bar and search display controller with segue

Never called when a search table cell is tapped
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"Show Detail"])
{
Player *player = [self.fetchedResultsController objectAtIndexPath:[self.tableView indexPathForSelectedRow]];
[segue.destinationViewController setPlayer:player];
}
}
This filters the list correctly, but the prepareForSegue is never called when a search table cell is tapped.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Player Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == self.tableView)
{
// normal table view population
Player *player = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[NSString alloc] initWithFormat:#"#%# %# %#", player.number, player.firstName, player.lastName];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"%#", player.position];
[cell.imageView setImageWithURL:[NSURL URLWithString:player.photo] placeholderImage:[UIImage imageNamed:#"playerplaceholder.jpg"]];
}
else if(tableView == self.searchDisplayController.searchResultsTableView)
{
// search view population
Player *player = [self.filteredFetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[NSString alloc] initWithFormat:#"#%# %# %#", player.number, player.firstName, player.lastName];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"%#", player.position];
[cell.imageView setImageWithURL:[NSURL URLWithString:player.photo] placeholderImage:[UIImage imageNamed:#"playerplaceholder.jpg"]];
}
return cell;
}
you need to put IF that check if the search have results.
like in this code:
if ([[segue identifier]isEqualToString:#"ShowDetails"])
{
ShowDetailsViewController *sdvc = (ShowDetailsViewController *)[segue destinationViewController];
NSIndexPath *indexPath = [[self tableView] indexPathForSelectedRow];
Books *selectedBooks = nil;
if(self.searchDisplayController.active)
selectedBooks = (Books *)[[self searchResults]objectAtIndex:[[[[self searchDisplayController]searchResultsTableView]indexPathForSelectedRow]row]];
else
selectedBooks = (Books *)[[self fetchResultsController] objectAtIndexPath:indexPath];
sdvc.currentBooks = selectedBooks;
}

Custom swipe function in UITableViewCell doesn't work

I need to add the count in the uitableviewcell in a such a way that when I trigger the swipe function the count should be incremented in the corresponding cell and while tapping the count should be decremented.
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
NSString *CellIdentifier = #"sample";
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
UISwipeGestureRecognizer *recognizer;
recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTapFrom:)];
[self addGestureRecognizer:recognizer];
self.tapRecognizer = (UITapGestureRecognizer *)recognizer;
recognizer.delegate = self;
[recognizer release];
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipeFrom:)];
[self addGestureRecognizer:recognizer];
[recognizer release];
UILabel *cookieLabel = [[UILabel alloc] initWithFrame:CGRectMake(5,5, 120,30)];
cookieLabel.text = #"hello";
cookieLabel.font = [UIFont systemFontOfSize:15.0f];
cookieLabel.textColor = [UIColor blackColor];
cookieLabel.backgroundColor = [UIColor redColor];
[cell.contentView addSubview:cookieLabel];
[cookieLabel release];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
costLabel = [[UILabel alloc] initWithFrame:CGRectMake( 200, 5, 230, 30)];
//costLabel.text = handleSwipeFrom:;
costLabel.font = [UIFont systemFontOfSize:15.0f];
costLabel.textColor = [UIColor blackColor];
costLabel.backgroundColor = [UIColor greenColor];
[cell.contentView addSubview:costLabel];
[costLabel release];
[self setUserInteractionEnabled:YES];
return cell;
}
Don't add the UISwipeGestureRecognizer to the cell. Add it to the UITableView.
I used TISwipeableTableView as a base and modified it heavily to work correctly (they did their own touch handling, which resulted in a "weird, unnative" feeling)
- (void)didSwipe:(UIGestureRecognizer *)gestureRecognizer {
if ([MRUserDefaults sharedMRUserDefaults].isSwipeMenuEnabled) {
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
CGPoint swipeLocation = [gestureRecognizer locationInView:self];
NSIndexPath *swipedIndexPath = [self indexPathForRowAtPoint:swipeLocation];
TISwipeableTableViewCell* swipedCell = (TISwipeableTableViewCell *)[self cellForRowAtIndexPath:swipedIndexPath];
if ([swipedCell isKindOfClass:[TISwipeableTableViewCell class]]) {
if (![swipedIndexPath isEqual:indexOfVisibleBackView]) {
[self hideVisibleBackView:YES];
[swipedCell revealBackView];
[self setIndexOfVisibleBackView:swipedIndexPath];
if (swipeDelegate && [swipeDelegate respondsToSelector:#selector(tableView:didSwipeCellAtIndexPath:)]){
[swipeDelegate tableView:self didSwipeCellAtIndexPath:[self indexPathForRowAtPoint:swipeLocation]];
}
}
}
}
}
}
- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
if ((self = [super initWithFrame:frame style:style])) {
if ([MRUserDefaults sharedMRUserDefaults].isSwipeMenuEnabled) {
UIGestureRecognizer *swipeGesture = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(didSwipe:)] autorelease];
[self addGestureRecognizer:swipeGesture];
}
}
return self;
}
This should get you started.
[cell addGestureRecognizer:recognizer]

Resources