Change image inside of a single UITableViewCell when button tapped in DetailViewController - ios

In my detail view controller (DetailViewController.m), a notification to change an image in a UITableViewCell type is fired. I have two types of UITableViewCells. That said, when acceptButton or declineButton is tapped, I ONLY want the image to change in 1 specific cell (specifically, an image in the tapped cell that opens the detail view - not in all cells of that type). How might I go about doing this? Here's my code so far:
DetailViewController.m
- (IBAction)acceptButton:(id)sender {
if (!checked1) {
[self.acceptCheck setImage:[UIImage imageNamed:#"checkedgreen.png"] forState:UIControlStateNormal];
checked1 = YES;
[[NSNotificationCenter defaultCenter] postNotificationName:#"ImageChangeNotification" object:nil];
AcceptedViewController *detailViewController = [[AcceptedViewController alloc]
initWithNibName:#"AcceptedViewController" bundle:nil];
[self presentViewController:detailViewController animated:YES completion:nil];
}
else if (checked1) {
[self.acceptCheck setImage:[UIImage imageNamed:#"uncheckedgray.png"] forState:UIControlStateNormal];
checked1 = NO;
}
}
- (IBAction)declineButton:(id)sender {
if (!checked2) {
[self.declineCheck setImage:[UIImage imageNamed:#"declinered.png"] forState:UIControlStateNormal];
checked2 = YES;
[[NSNotificationCenter defaultCenter] postNotificationName:#"Declined" object:nil];
DeniedViewController *detailViewController = [[DeniedViewController alloc]
initWithNibName:#"DeniedViewController" bundle:nil];
[self presentViewController:detailViewController animated:YES completion:nil];
}
else if (checked2) {
[self.declineCheck setImage:[UIImage imageNamed:#"declinegray.png"] forState:UIControlStateNormal];
checked2 = NO;
}
}
TableViewCellB.m
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(changeImage)
name:#"ImageChangeNotification"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(declineImage)
name:#"Declined"
object:nil];
}
-(void)changeImage
{
[self.displayedBar setImage:[UIImage imageNamed:#"greenbar.png"]];
self.Title.text = #"Accepted!";
}
-(void)declineImage
{
[self.displayedBar setImage:[UIImage imageNamed:#"redbar.png"]];
self.Title.text = #"Declined!";
}
TableViewController.m (incase it's needed)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *data = self.messages[indexPath.row];
id swaptime = data[#"swaptime"];
if ([swaptime isKindOfClass:[NSString class]]) {
static NSString *ChatTableIdentifier2 = #"SwapDetailTableViewCell";
SwapDetailTableViewCell *cell = (SwapDetailTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier2 forIndexPath:indexPath];
NSString *time = data[#"swaptime"];
cell.startTime.text = time;
NSString *timeEnd = data[#"endswaptime"];
cell.endTime.text = timeEnd;
NSString *costofSwap = data[#"swapvalue"];
cell.swapValue.text = costofSwap;
return cell;
} else {
static NSString *ChatTableIdentifier = #"ChatTableViewCell";
ChatTableViewCell *cell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier forIndexPath:indexPath];
NSString *userName = data[#"name"];
cell.sendingUser.text = userName;
NSString *messageBody = data[#"body"];
cell.messageDisplayed.text = messageBody;
NSString *timeReceived = data[#"published at"];
cell.timeStamp.text = timeReceived;
NSString *userInfo = [self.userid objectForKey:#"name"];
if ([cell.sendingUser.text isEqual: userInfo]) {
cell.messageDisplayed.textAlignment = NSTextAlignmentLeft;
cell.sendingUser.textAlignment = NSTextAlignmentLeft;
[cell.chatBubble setImage:[UIImage imageNamed:#"bubblegrey2.png"]];
} else {
cell.messageDisplayed.textAlignment = NSTextAlignmentRight;
cell.sendingUser.textAlignment = NSTextAlignmentRight;
[cell.chatBubble setImage:[UIImage imageNamed:#"bubbleorange2.png"]];
}
return cell;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *data = self.messages[indexPath.row];
id swaptime = data[#"swaptime"];
if ([swaptime isKindOfClass:[NSString class]]) {
SwapDetailsViewController *detailViewController = [[SwapDetailsViewController alloc]
initWithNibName:#"SwapDetailsViewController" bundle:nil];
detailViewController.indexPath = [self.tableView indexPathForSelectedRow];
detailViewController.delegate = self;
detailViewController.swapDetails = [self.messages objectAtIndex:indexPath.row];
[self presentViewController:detailViewController animated:YES completion:nil];
} else {
}
}

#interface DetailViewController ()
{
UIImage *_yourImage;
}
Then change it how u need it in declineButton or acceptButton and do [tableView reloadData].

In DetailViewController.h create protocol and create a property of it as below.
#protocol DetailViewControllerDelegate <NSObject>
- (void)acceptButton:(BOOL)accepted withIndexPath:(NSIndexPath*)indexPath;
#end
#interface DetailViewController : UIViewController
#property (strong, nonatomic) NSIndexPath *indexPath;
#property (weak, nonatomic) id<DetailViewControllerDelegate> delegate;
// other properites and methods ....
#end
IN MasterViewController
While pushing detailViewController pass the indexpath and set the delegete to self and confirm, implement delegate method, as below
#interface MasterViewController () <DetailViewControllerDelegate>
// other properties....
#end
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"showDetail"]) {
DetailViewController *controller = (DetailViewController *)[[segue destinationViewController] topViewController];
controller.indexPath = [self.tableView indexPathForSelectedRow];
controller.delegate = self;
// Other code...
}
}
- (void)acceptButton:(BOOL)accepted withIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (accepted) {
// do accepted stuff
} else {
// do decline stuff
}
}
IN DetailViewController.m
Implement the accept and decline button action
- (IBAction)acceptButton:(id)sender {
if (!checked1) {
[self.acceptCheck setImage:[UIImage imageNamed:#"checkedgreen.png"] forState:UIControlStateNormal];
checked1 = YES;
/// calling delegate method
[self.delegate acceptButton:YES withIndexPath:self.indexPath];
AcceptedViewController *detailViewController = [[AcceptedViewController alloc]
initWithNibName:#"AcceptedViewController" bundle:nil];
[self presentViewController:detailViewController animated:YES completion:nil];
} else if (checked1) {
[self.acceptCheck setImage:[UIImage imageNamed:#"uncheckedgray.png"] forState:UIControlStateNormal];
checked1 = NO;
}
}
- (IBAction)declineButton:(id)sender {
if (!checked2) {
[self.declineCheck setImage:[UIImage imageNamed:#"declinered.png"] forState:UIControlStateNormal];
checked2 = YES;
/// calling delegate method
[self.delegate acceptButton:NO withIndexPath:self.indexPath];
DeniedViewController *detailViewController = [[DeniedViewController alloc]
initWithNibName:#"DeniedViewController" bundle:nil];
[self presentViewController:detailViewController animated:YES completion:nil];
} else if (checked2) {
[self.declineCheck setImage:[UIImage imageNamed:#"declinegray.png"] forState:UIControlStateNormal];
checked2 = NO;
}
}

Related

iOS Obj-C - UITableView data disappears when modal view dismissed

I have a uitableview inside of a view controller, and a button underneath of my uitableview. Tapping this button opens a modal view. I've created a "close" button inside my modal using the following code:
modalview.m
- (IBAction)closeButton:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
However when I tap to dismiss my modal view, all of the data in my uitableview seems to disappear (the uitableview just goes white)? Any idea why this might be, and how can I fix it? Here is how my tableview data is loaded and structured (hope this helps):
ViewController.m
-(void)updateMessages {
self.tableView.dataSource = self;
NSMutableDictionary *viewParams = [NSMutableDictionary new];
[viewParams setValue:#"name" forKey:#"view_name"];
[DIOSView viewGet:viewParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.messages = (NSMutableArray *)responseObject;
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", [error localizedDescription]);
}];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self updateMessages];
static NSString *ChatTableIdentifier = #"ChatTableViewCell";
static NSString *ChatTableIdentifier2 = #"SwapDetailTableViewCell";
UINib *nib = [UINib nibWithNibName: ChatTableIdentifier bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier: ChatTableIdentifier];
UINib *nib2 = [UINib nibWithNibName: ChatTableIdentifier2 bundle:nil];
[self.tableView registerNib:nib2 forCellReuseIdentifier: ChatTableIdentifier2];
self.tableView.dataSource = self;
[self.tableView reloadData];
}
- (int)numberOfSectionsInTableView: (UITableView *)tableview
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.messages count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *data = self.messages[indexPath.row];
id swaptime = data[#"swaptime"];
if ([swaptime isKindOfClass:[NSString class]]) {
// There is a valid "swaptime" value
static NSString *ChatTableIdentifier2 = #"SwapDetailTableViewCell";
SwapDetailTableViewCell *cell = (SwapDetailTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier2 forIndexPath:indexPath];
NSString *time = data[#"swaptime"];
cell.startTime.text = time;
NSString *timeEnd = data[#"endswaptime"];
cell.endTime.text = timeEnd;
NSString *costofSwap = data[#"swapvalue"];
cell.swapValue.text = costofSwap;
NSString *fromUsername = data[#"first name"];
cell.fromUser.text = fromUsername;
NSString *pet = data[#"pet's name"];
cell.petsname.text = pet;
NSString *swapStatus = data[#"swapaccepted"];
if ([swapStatus isEqual: #"Yes"]) {
[cell.displayedBar setImage:[UIImage imageNamed:#"greenbar.png"]];
cell.swapTitle.text = #"Accepted!";}
else {
if ([swapStatus isEqual: #""]) {
[cell.displayedBar setImage:[UIImage imageNamed:#"orangecellbar.png"]];
cell.swapTitle.text = #"You have a Request!";}
if ([swapStatus isEqual: #"Requested"]) {
[cell.displayedBar setImage:[UIImage imageNamed:#"orangecellbar.png"]];
cell.swapTitle.text = #"You have a Request!";}
if ([swapStatus isEqual: #"Cancelled"]) {
[cell.displayedBar setImage:[UIImage imageNamed:#"blueecellbar.png"]];
cell.swapTitle.text = #"Cancelled!";}
if ([swapStatus isEqual: #"No"]) {
[cell.displayedBar setImage:[UIImage imageNamed:#"redbar.png"]];
cell.swapTitle.text = #"Declined!";
}
}
return cell;
} else {
static NSString *ChatTableIdentifier = #"ChatTableViewCell";
ChatTableViewCell *cell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ChatTableIdentifier forIndexPath:indexPath];
NSString *userName = data[#"first name"];
cell.sendingUser.text = userName;
NSString *messageBody = data[#"body"];
cell.messageDisplayed.text = messageBody;
NSString *timeReceived = data[#"published at"];
cell.timeStamp.text = timeReceived;
NSString *userInfo = [self.userid objectForKey:#"first name"];
if ([cell.sendingUser.text isEqual: userInfo]) {
cell.messageDisplayed.textAlignment = NSTextAlignmentLeft;
cell.sendingUser.textAlignment = NSTextAlignmentLeft;
[cell.chatBubble setImage:[UIImage imageNamed:#"bubblegrey2.png"]];
} else {
cell.messageDisplayed.textAlignment = NSTextAlignmentRight;
cell.sendingUser.textAlignment = NSTextAlignmentRight;
[cell.chatBubble setImage:[UIImage imageNamed:#"bubbleorange2.png"]];
}
return cell;
}
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self.tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
}
The problem is probably in your viewDidAppear, try replace:
[self.tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
with:
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.messages count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
or properly calculate the height, probably it's:
self.tableView.contentView.height

Display XIB erorr nil

I am new to Swift and I am beginning to learn XIB. I want to pressing the button appears XIB.
I using liberty ARSPopover
my error :
Warning: Attempt to present on
which is already
presenting (null)
How can I solve this problem?
My code for button :
- (IBAction)btnShoPopover:(UIBarButtonItem *)sender {
ARSPopover *popoverController = [ARSPopover new];
popoverController.sourceView = self.view;
popoverController.sourceRect = CGRectMake(370,0, 0, 0);
popoverController.contentSize = CGSizeMake(200,300);
popoverController.arrowDirection = UIPopoverArrowDirectionUp;
[self presentViewController:popoverController animated:YES completion:^{
[popoverController insertContentIntoPopover:^(ARSPopover *popover, CGSize popoverPresentedSize, CGFloat popoverArrowHeight) {
PopovViewController *poper = [[PopovViewController alloc] init];
[self presentViewController:poper animated:YES completion:nil];
}];
}];
}
I my xib don't download:
My code for xib controller:
#interface PopovViewController ()
#end
#implementation PopovViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
My controller:
#import "ResourseTableViewController.h"
#import "ProbaViewController.h"
#interface ResourseTableViewController ()
#end
#implementation ResourseTableViewController
#synthesize arrayOriginal;
#synthesize arForTable;
- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *dTmp=[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"data" ofType:#"plist"]];
self.arrayOriginal=[dTmp valueForKey:#"Objects"];
self.arForTable=[[NSMutableArray alloc] init] ;
[self.arForTable addObjectsFromArray:self.arrayOriginal];
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.sidebarButton setTarget: self.revealViewController];
[self.sidebarButton setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.arForTable count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
[cell setIndentationLevel:[[[self.arForTable objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *d=[self.arForTable objectAtIndex:indexPath.row];
NSLog(#"Selected index data %#",d);
if([d valueForKey:#"Objects"]) {
NSArray *ar=[d valueForKey:#"Objects"];
BOOL isAlreadyInserted=NO;
for(NSDictionary *dInner in ar ){
NSInteger index=[self.arForTable indexOfObjectIdenticalTo:dInner];
isAlreadyInserted=(index>0 && index!=NSIntegerMax);
if(isAlreadyInserted) break;
}
if(isAlreadyInserted) {
[self miniMizeThisRows:ar];
} else {
NSUInteger count=indexPath.row+1;
NSMutableArray *arCells=[NSMutableArray array];
for(NSDictionary *dInner in ar ) {
[arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
[self.arForTable insertObject:dInner atIndex:count++];
}
[tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationNone];
}
}
}
- (IBAction)btnPopover:(id)sender {
ARSPopover *popoverController = [ARSPopover new];
popoverController.sourceView = self.view;
popoverController.sourceRect = CGRectMake(370,0, 0, 0);
popoverController.contentSize = CGSizeMake(200,300);
popoverController.arrowDirection = UIPopoverArrowDirectionUp;
[self presentViewController:popoverController animated:NO completion:^{
[popoverController insertContentIntoPopover:^(ARSPopover *popover, CGSize popoverPresentedSize, CGFloat popoverArrowHeight) {
ProbaViewController *poper = [[ProbaViewController alloc] init];
CGFloat width = popoverPresentedSize.width;
CGFloat height = popoverPresentedSize.height - popoverArrowHeight;
poper.view.frame = CGRectMake(0, 0, width, height);
popover.view.layer.backgroundColor = [UIColor clearColor].CGColor;
[popover.view addSubview:poper.view];
}];
}];
}
-(void)miniMizeThisRows:(NSArray*)ar{
for(NSDictionary *dInner in ar ) {
NSUInteger indexToRemove=[self.arForTable indexOfObjectIdenticalTo:dInner];
NSArray *arInner=[dInner valueForKey:#"Objects"];
if(arInner && [arInner count]>0){
[self miniMizeThisRows:arInner];
}
if([self.arForTable indexOfObjectIdenticalTo:dInner]!=NSNotFound) {
[self.arForTable removeObjectIdenticalTo:dInner];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:
[NSIndexPath indexPathForRow:indexToRemove inSection:0]
]
withRowAnimation:UITableViewRowAnimationNone];
}
}
}
#end
Skimming the docs, it looks like the library is very versatile with respect to what's presented in the popover. Your code provides a clue that you hope to present a custom view controller within it (a PopovViewController).
EDIT Let's find out first where the problem lies. If everything else is working properly, then this code should present a green box...
[self presentViewController:popoverController animated:YES completion:^{
[popoverController insertContentIntoPopover:^(ARSPopover *popover, CGSize popoverPresentedSize, CGFloat popoverArrowHeight) {
CGFloat width = popoverPresentedSize.width;
CGFloat height = popoverPresentedSize.height - popoverArrowHeight;
UIView *test = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
test.backgroundColor = [UIColor greenColor];
[popover.view addSubview:test];
}];
}];
If that works, we can proceed to discovering why your PopovViewController's view is causing trouble. (My guess is that it's presentation is triggering some other presentation animation that conflicts with the 3rd party library.
If you get a working green view with no warnings or errors, post the code for PopovViewController's viewDidLoad, viewWillAppear, ...didAppear, ...didLayout, etc.

Global array with custom objects is not keeping objects' state

I am creating a bucket list app and I need to be able to save each BucketListGoal from a UITextField in a UITableViewCell. Here is my relevant code below -
#interface BucketListGoalViewController () <UITableViewDataSource, UITableViewDelegate, CreateGoalTableViewCellDelegate, UITextFieldDelegate, UIPopoverPresentationControllerDelegate>
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (strong, nonatomic) NSArray *goals;
#property NSInteger path;
#end
#implementation BucketListGoalViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.navigationItem.title = #"Goals";
self.count = 0;
self.goals = [[NSArray alloc] init];
[self createNewGoal];
self.tableView.allowsSelection = NO;;
[self.tableView registerClass:[CreateGoalTableViewCell class]forCellReuseIdentifier:#"Cell"];
[self.tableView registerNib:[UINib nibWithNibName:#"CreateGoalTableViewCell" bundle:nil] forCellReuseIdentifier:#"Cell"];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(handleCoordinatesFromBucketList:)
name:#"Coordinates"
object:nil];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"Cell";
CreateGoalTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
[cell.textField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
cell.tag = indexPath.row;
cell.delegate = self;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textField.tag = indexPath.row;
cell.textField.delegate = self;
BucketListGoal *goal = [self.goals objectAtIndex:indexPath.row];
goal.tag = indexPath.row;
if (goal.address != nil) {
[cell.locationButton setTitle:goal.address forState:UIControlStateNormal];
}
goal.name = cell.detailTextLabel.text;
cell.textField.placeholder = #"Write the description of your goal here.";
cell.numberLabel.text = [NSString stringWithFormat:#"%ld)", (long)indexPath.row + 1];
return cell;
}
-(void)createNewGoal {
BucketListGoal *goal = [BucketListGoal new];
NSMutableArray *copy = [self.goals mutableCopy];
[copy addObject:goal];
self.goals = copy;
[self.tableView reloadData];
}
-(void)textFieldDidChange:(UITextField *)textField{
NSMutableArray *copy = [self.goals mutableCopy];
BucketListGoal *goal = [self.goals objectAtIndex:textField.tag];
goal.name = textField.text;
[copy replaceObjectAtIndex:textField.tag withObject:goal];
self.goals = copy;
}
I create the goal from a bar button item at the top of the view. The issue is that self.goals is only keeping the goal.name of the latest item of the array. All the other previous items from the text fields continue being nil. What am I missing here?

How Do I Display The Description Of An In-App Purchase Item?

I have a MasterViewController that shows a list of In-App Purchases in a table view. Whenever the table view cell is clicked, it presents my DetailViewController but it doesn't present the localized detail description for that In-App Purchase item. Is there a way so that depending on which IAP item was pressed in the tableview cell, it will present that IAP item's description in the DVC?
Here is my MVC.m:
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "RageIAPHelper.h"
#import <StoreKit/StoreKit.h>
#interface MasterViewController () {
NSArray *_products;
NSNumberFormatter * _priceFormatter;
}
#end
#implementation MasterViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStylePlain target:nil action:nil];
[self.navigationItem setBackBarButtonItem:backButtonItem];
self.title = #"Settings";
self.refreshControl = [[UIRefreshControl alloc] init];
[self.refreshControl addTarget:self action:#selector(reload) forControlEvents:UIControlEventValueChanged];
[self reload];
[self.refreshControl beginRefreshing];
_priceFormatter = [[NSNumberFormatter alloc] init];
[_priceFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[_priceFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Restore" style:UIBarButtonItemStylePlain target:self action:#selector(restoreTapped:)];
}
- (void)restoreTapped:(id)sender {
[[RageIAPHelper sharedInstance] restoreCompletedTransactions];
}
- (void)viewWillAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(productPurchased:) name:IAPHelperProductPurchasedNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)productPurchased:(NSNotification *)notification {
NSString * productIdentifier = notification.object;
[_products enumerateObjectsUsingBlock:^(SKProduct * product, NSUInteger idx, BOOL *stop) {
if ([product.productIdentifier isEqualToString:productIdentifier]) {
[self.tableView reloadRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:idx inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
*stop = YES;
}
}];
}
- (void)reload {
_products = nil;
[self.tableView reloadData];
[[RageIAPHelper sharedInstance] requestProductsWithCompletionHandler:^(BOOL success, NSArray *products) {
if (success) {
_products = products;
[self.tableView reloadData];
}
[self.refreshControl endRefreshing];
}];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _products.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
SKProduct * product = (SKProduct *) _products[indexPath.row];
cell.textLabel.text = product.localizedTitle;
[_priceFormatter setLocale:product.priceLocale];
cell.detailTextLabel.text = [_priceFormatter stringFromNumber:product.price];
if ([[RageIAPHelper sharedInstance] productPurchased:product.productIdentifier]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.accessoryView = nil;
} else {
UIButton *buyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buyButton.frame = CGRectMake(0, 0, 72, 37);
[buyButton setTitle:#"Buy" forState:UIControlStateNormal];
buyButton.tag = indexPath.row;
[buyButton addTarget:self action:#selector(buyButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.accessoryView = buyButton;
}
return cell;
}
- (void)buyButtonTapped:(id)sender {
UIButton *buyButton = (UIButton *)sender;
SKProduct *product = _products[buyButton.tag];
NSLog(#"Buying %#...", product.productIdentifier);
[[RageIAPHelper sharedInstance] buyProduct:product];
}
#end
And here is my DetailViewController.h:
#import <UIKit/UIKit.h>
#interface DetailViewController : UIViewController
#property (strong, nonatomic) id detailItem;
#property (weak, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
#end
And my DetailViewController.m:
#import "DetailViewController.h"
#interface DetailViewController ()
- (void)configureView;
#end
#implementation DetailViewController
#pragma mark - Managing the detail item
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
self.detailDescriptionLabel.text = [self.detailItem description];
_detailDescriptionLabel.text = #"Please enable in app purchase in your settings";
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
You should add this method your MasterVC.m
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
DetailViewController *dest = [segue destinationViewController];
UITableViewCell *cell = (UITableViewCell*)sender;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
SKProduct *product = (SKProduct *) _products[indexPath.row];
dest.detailText = product.localizedDescription;
}
In DetailVC.h add:
#property (nonatomic, readwrite) NSString *detailText;
In DetailVC.m add:
- (void)viewWillAppear:(BOOL)animated {
self.detailDescriptionLabel.text = detailText;
}
Make sure you import your DetailViewController.h at the top of your MasterVC.m file.

how to push tableview to UIView dynamically in iOS?

i am displaying list content in table view now i want when i click
one menu of list that menu content display in UIView on next screen
. how to push UITableView to UIView dynamically in iOS.
#import "SmsCategoryTitleTableViewController.h"
#import "CategoryMainWindowViewController.h"
#import "AppDelegate.h"
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "SmsTitle.h"
#import "SMSCategory.h"
#import"smsDisplayViewController.h"
#interface SmsCategoryTitleTableViewController ()
#end
#implementation SmsCategoryTitleTableViewController
#synthesize theSearchBar,Id;
#synthesize theTableView;
#synthesize array;
#synthesize disableViewOverlay;
#synthesize Arrayobject;
- (void)viewDidLoad
{
[super viewDidLoad];
[self SearchBarCode];
[self GetTableData];
[self.tableView reloadData];
filteredContentList = [[NSMutableArray alloc] init];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
// [self performSelector:#selector(push:) withObject:nil afterDelay:0.2f];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
-(void)GetTableData
{
array = [[NSMutableArray alloc] init];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentDir = [docPaths objectAtIndex:0];
self.databasePath = [documentDir stringByAppendingPathComponent:#"SMS.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:self.databasePath];
[database setLogsErrors:TRUE];
[database open];
NSString *anQuery = [[NSString alloc]initWithFormat:#"SELECT * FROM SMSnJokes
where CategoryId=%#",self.Id];
FMResultSet *results = [database executeQuery:anQuery];
while([results next])
{
SmsTitle *title=[[SmsTitle alloc]init];
title.Id = [results stringForColumn:#"Id"];
title.CategoryId = [results stringForColumn:#"CategoryId"];
title.Title = [results stringForColumn:#"Title"];
[array addObject:title];
// NSLog(#"SMS LIST %#",title.Title);
}
[database close];
}
-(void)SearchBarCode
{
self.disableViewOverlay = [[UIView
alloc]initWithFrame:CGRectMake(0.0f,44.0f,320.0f,0)];
self.disableViewOverlay.backgroundColor=[UIColor lightGrayColor];
self.disableViewOverlay.alpha = 0;
theSearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 5, 374.0f, 50)];
theSearchBar.delegate =self;
[self.tableView addSubview:theSearchBar];
self.navigationItem.title=#"SMS LIST";
[[self tableView] setTableHeaderView:theSearchBar];
}
- (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.
if (isSearching)
{
return [filteredContentList count];
}
else
{
return [array count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"Cell";
UITableViewCell *cell=[tableView
dequeueReusableCellWithIdentifier:CellIdentifier ];
if(!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] ;
}
if (isSearching)
{
cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else
{
SmsTitle *title = [array objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"%# ",[title
valueForKey:#"Title"]]];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)searchTableList
{
NSString *searchString =theSearchBar.text;
filteredContentList = [[NSMutableArray alloc]init];
[filteredContentList removeAllObjects];
for (SmsTitle *title in array)
{
NSString *tempStr = title.Title;
NSComparisonResult result = [tempStr compare:searchString options:
(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0,
[searchString length])];
if (result == NSOrderedSame)
{
[filteredContentList addObject:title.Title];
}
}
}
#pragma mark - Search Implementation
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self.theSearchBar resignFirstResponder];
}
- (void) dismissKeyboard
{
[self.theSearchBar becomeFirstResponder];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
isSearching = YES;
[theSearchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSLog(#"Text change - %d",isSearching);
//Remove all objects first.
[filteredContentList removeAllObjects];
if([searchText length] != 0) {
isSearching = YES;
[self searchTableList];
}
else {
isSearching = NO;
}
[self.tableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
theSearchBar.text=nil;
[theSearchBar setShowsCancelButton:NO animated:YES];
[theSearchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[theSearchBar setShowsCancelButton: YES animated: YES];
[self searchTableList];
[searchBar resignFirstResponder];
}
- (void)searchBar:(UISearchBar *)searchBar activate:(BOOL) active
{
self.theTableView.allowsSelection = !active;
self.theTableView.scrollEnabled = !active;
if (!active)
{
[disableViewOverlay removeFromSuperview];
[searchBar resignFirstResponder];
}
else
{
self.disableViewOverlay.alpha = 0;
[self.view addSubview:self.disableViewOverlay];
[UIView beginAnimations:#"FadeIn" context:nil];
[UIView setAnimationDuration:0.5];
self.disableViewOverlay.alpha = 0.6;
[UIView commitAnimations];
NSIndexPath *selected = [self.theTableView indexPathForSelectedRow];
if (selected)
{
[self.theTableView deselectRowAtIndexPath:selected
animated:NO];
}
}
[searchBar setShowsCancelButton:active animated:YES];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
[self.theSearchBar resignFirstResponder];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
textField.returnKeyType=UIReturnKeyDefault ;
return[textField resignFirstResponder];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
*)indexPath
{
smsDisplayViewController *viewController1 = [[smsDisplayViewController alloc]
init];
[self.navigationController pushViewController:viewController1 animated:YES];
}
Ok got your point. I think you want to pass data of selected cell to
next UIViewController. Assume, you want to pass cell title label and
you have an array of objects. In yoursmsDisplayViewController.h
#import <UIKit/UIKit.h>
#interface smsDisplayViewController : UIViewController
#property (strong, nonatomic) NSString *cellName;
Now in your SmsCategoryTitleTableViewController.m you have
NSMutableArray *nameList;
Then in your table view delegate method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
smsDisplayViewController *viewController1 = [self.storyboard instantiateViewControllerWithIdentifier:#"LoginIdentifier"];
viewController1.cellName=[nameList objectAtIndex:indexPath.row];
[self.navigationController pushViewController:viewController1 animated:YES];
}
UPDATE This is the code you posted first in your question.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
smsDisplayViewController *viewController1 = [[smsDisplayViewController
alloc] initWithNibName:#"viewController1" bundle:nil];
[self.navigationController pushViewController:viewController1 animated:YES];
}
Now the wrong thing you are doing here
isinitWithNibName:#"viewController1". If you are not using any nib
file then your code should be
smsDisplayViewController *viewController1 = [[smsDisplayViewController alloc] init];
[self.navigationController pushViewController:viewController1 animated:YES];
You can use Accessory Buttons in UITableView or learn more about segues.
You have to use prepareForSegue: to pass data to another ViewController.
You can learn it from Here which teaches you how to transfer data between ViewControllers while using Segue.

Resources