I'd like to implement a "like" functionality in a table view. Each row has a like button and a like counter.
When the user taps "like" the like counter should be increased by one. If the same user taps again, the like counter is decreased by one.
I have implemented this using reloadRowsAtIndexPaths. However, this reloads the whole cell and it is bad in terms of usability.
Would you know a simple mechanism to implement such a functionality? The main requirement is that only the like counter is updated, not the whole cell or table.
Thanks in advance,
Tiago
U don't need to reload a whole cell, simply change the title/image for your like button.
Smth. like this:
#pragma mark - custom table cell
#interface TableCellWithLikeButton : UITableViewCell
#property (weak, nonatomic) IBOutlet UIButton *userLikeButton;
#end
#implementation TableCellWithLikeButton
#end
#pragma mark - User modal
#interface User:NSObject
#property (assign, nonatomic) BOOL wasLiked;
#property (assign, nonatomic) NSInteger likesCounter;
#end
#implementation User
#end
#implementation VC1
{
IBOutlet UITableView *_tableView;
NSMutableArray *_users;
}
- (id)initWithCoder:(NSCoder*)aDecoder
{
if(self = [super initWithCoder:aDecoder]) {
_users = [NSMutableArray array];
for (int i=0;i<100;i++) {
User *user = [User new];
[_users addObject:user];
}
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _users.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"CellWithLikeButton";
TableCellWithLikeButton *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
[cell.userLikeButton addTarget:self action:#selector(changeLikeStatus:) forControlEvents:UIControlEventTouchUpInside];
User *user = _users[indexPath.row];
[cell.userLikeButton setTitle:user.wasLiked?#"Liked":#"Like" forState:UIControlStateNormal];
cell.userLikeButton.tag = indexPath.row;
return cell;
}
- (void)changeLikeStatus:(UIButton *)likeButton
{
User *user = _users[likeButton.tag];
user.likesCounter += user.wasLiked?-1:1;
user.wasLiked = !user.wasLiked;
[likeButton setTitle:user.wasLiked?#"Liked":#"Like" forState:UIControlStateNormal];
}
#end
Related
I'm using the UITableview like below image. If i typing Unit price and Qty i need to calculate. But now i dont know how to get indexpath for two text box in UITableView . In UITableView if button clicking goes to didSelectRowAtIndexPath method. Same method not calling when I typing in qty and unitprice textbox.
InvoiceMainViewController.h
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#class InvoiceGridViewController;
#protocol InvoiceTableCellProtocoll <NSObject>
-(void) didPressButton:(InvoiceGridViewController *)theCell;
#end
#interface InvoiceGridViewController : UITableViewCell {
id<InvoiceTableCellProtocoll> delegationListener; }
#property (nonatomic,assign) id<InvoiceTableCellProtocoll> delegationListener;
#property (nonatomic,retain) IBOutlet UITextField *invoiceItem;
#property (nonatomic,retain) IBOutlet UITextField *invoiceUnitPrice;
#property (nonatomic,retain) IBOutlet UITextField *invoiceQty;
#property (nonatomic,retain) IBOutlet UITextField *invoiceTaxRate;
#property (nonatomic,retain) IBOutlet UILabel *invoiceItemId;
#property (nonatomic,retain) IBOutlet UILabel *invoiceCurrencyId;
#property (nonatomic,retain) IBOutlet UILabel *invoiceTaxRateId;
#property (nonatomic,retain) IBOutlet UILabel *totalItemTax; #property
#property (nonatomic,retain) IBOutlet UILabel *converstionMessage;
-(IBAction)deleteSel:(id)sender;
-(void)delFileSel;
#end
InvoiceMainViewController.m
#import <UIKit/UIKit.h>
#import "SBPickerSelector.h"
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperationManager.h"
#import "AFURLResponseSerialization.h"
#import "AFURLRequestSerialization.h"
#import "InvoiceGridViewController.h"
#interface InvoiceMainViewController : UIViewController<UITableViewDataSource, UITableViewDelegate,NSXMLParserDelegate,UITextFieldDelegate,InvoiceTableCellProtocoll>{
you can do this in various methods
Type -1
// get the current visible rows
NSArray *paths = [yourtableName indexPathsForVisibleRows];
NSIndexPath *indexpath = (NSIndexPath*)[paths objectAtIndex:0];
Type-2
you can get which cell you touched
CGPoint touchPoint = [sender convertPoint:CGPointZero toView: yourtableName];
NSIndexPath *clickedButtonIndexPath = [mainTable indexPathForRowAtPoint: yourtableName];
Type-3
add `TapGestuure ` for get the current cell.
Type-4
- (void) textFieldDidEndEditing:(UITextField *)textField {
CGRect location = [self convertRect:textField.frame toView:self.tableView];
NSIndexPath *indexPath = [[self.tableView indexPathsForRowsInRect:location] objectAtIndex:0];
// Save the contents of the text field into your array:
[yourArray replaceObjectAtIndex:indexPath.row withObject:textField.text];
}
example
here if you need additional information see this link
Try this one
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
firstTxt.delegate = self;
secondTxt.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
NSLog(#"textFieldShouldBeginEditing");
textField.backgroundColor = [UIColor colorWithRed:220.0f/255.0f green:220.0f/255.0f blue:220.0f/255.0f alpha:1.0f];
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
NSLog(#"textFieldDidBeginEditing");
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
NSLog(#"textFieldShouldEndEditing");
textField.backgroundColor = [UIColor whiteColor];
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
NSLog(#"textFieldDidEndEditing");
[tableView reloadData];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(#"touchesBegan:withEvent:");
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
}
#pragma mark -
#pragma mark - UITableView Delegates
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:#"FirstTableViewCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"FirstTableViewCell"];
// cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if (![firstTxt.text isEqual: #""] && ![secondTxt.text isEqual: #""])
{
NSString *fir = firstTxt.text;
NSString * sec = secondTxt.text;
cell.textLabel.text= [NSString stringWithFormat:#"%d",[fir intValue]+[sec intValue]];
}
else
{
cell.textLabel.text=#"";
}
//etc.
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 4;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// NSLog(#"testing1");
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.layer.backgroundColor = [UIColor clearColor].CGColor;
cell.backgroundColor = [UIColor clearColor];
}
#end
.h
//
// ViewController.h
// TestingText
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
IBOutlet UITableView *tableView;
IBOutlet UITextField *secondTxt;
IBOutlet UITextField *firstTxt;
}
#end
In textfield delegate method you can get the indexpath of row or you can directly get the textfields text
-(void)textFieldDidEndEditing:(UITextField *)textField
{
CGPoint hitPoint = [txtfield convertPoint:CGPointZero toView:tbl];
hitIndex = [tbl indexPathForRowAtPoint:hitPoint];
int localCount = [txtfield.text intValue];
}
Subclass your UITableViewCells. Create a protocol for each cell, with methods like cellName:(UITableViewCell*)cellName didSelectItem:(Item*) item. You can find more info here.
In the UITableViewCell set your UITextView delegate to self, and implement the protocol. textFieldShouldReturn: method, will indicate when the user is typing, so inside you will call [self.delegate cellName:self didEditText:textField.text].
In your MainViewController tableView: cellForRowAtIndexPath: set the UITabelViewCell's delegates, and implement the protocols.
So you will know in MainViewController when a user has typed in any of your textfields, independently from the table row number.
I have a table view controller with three cells, each with a textfield where a user defines:
-Country
-State (disabled)
-City (disabled)
How do I enable "State" textfield after the user types in "Country"?
The main problem is that I'm using a model called "Field", which has a property called "depends", which shows the id of the other Field that must not be empty.
My custom table view cell has a property "Field".
If I use "textfieldDidBeginEditing()" I can only access the textfield inside the cell, not the "Field" property.
All my cells are created dynamically.
The project is in Objective-C.
Its quite easy, here are your steps
Set textfield.delegate to your UIViewController
Implement UITextFieldDelegate method - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
Check for text length if needed
Grab next cell that u would like to enable using following code:
UITableViewCell *thisCell = [textView superCell];
NSIndexPath *thisIndexPath = [tableView indexPathForCell:thisCell];
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:thisIndexPath.row inSection:thisIndexPath.section];
UITableViewCell *nextCell = [tableView cellForRowAtIndexPath: nextIndexPath];
Call becomeFirstResponder for a textField inside nextCell
You will need to create an UIView category with following method for code above to work
- (UITableViewCell *)superCell {
UIView *cell = self;
do {
cell = cell.superview;
} while( ![cell isKindOfClass:[UITableViewCell class]] && cell != nil );
return (UITableViewCell *)cell;
}
Short and simple:
For short list like your (table view can place all cells on the screen) it's will be enough to keep references to all three fields:
// Your model
#interface AddressStorageModel : NSObject
#property (strong, nonatomic) NSString* country;
#property (strong, nonatomic) NSString* state;
#property (strong, nonatomic) NSString* city;
#end
// Your cell
#interface FieldTableCell : UITableViewCell
#property (readonly, nonatomic) UITextField* textField;
#end
// Your view controller implementation
#implementation ViewController
{
__weak UITextField* _countryField;
__weak UITextField* _stateField;
__weak UITextField* _cityField;
AddressStorageModel* _addressStorage;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FieldTableCell *cell = (FieldTableCell*)[tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
cell.textField.delegate = self;
switch (indexPath.row) {
case 0: // Country
_countryField = cell.textField;
break;
case 1: // State
_stateField = cell.textField;
break;
case 2: // City
_cityField = cell.textField;
break;
}
return cell;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
// Validate somehow and move cursor to next field:
if (textField.text.length) {
UITextField* nextTextField = [self p_textFieldNextTo:textField];
[nextTextField setEnabled:YES];
[nextTextField becomeFirstResponder];
}
}
- (UITextField *)p_textFieldNextTo:(UITextField *)textField
{
if (textField == _countryField)
return _stateField;
else if (textField == _stateField)
return _cityField;
return _countryField;
}
- (void)completeButtonAction:(id)sender
{
_addressStorage.country = _countryField.text;
_addressStorage.state = _stateField.text;
_addressStorage.city = _cityField.text;
}
More complicated ... but simpler for future support
But if you plan to increase number of fields you should implement your code in this way:
// Your model
#interface AddressField : NSObject
#property (strong, nonatomic) NSString* title;
#property (strong, nonatomic) NSString* value;
#property (strong, nonatomic) AddressField* dependency;
#property (strong, nonatomic) NSIndexPath* indexPath;
#end
// Your cell
#protocol FieldTableCellDelegate <NSObject>
#required
- (void)fieldCellDidEndEditing:(FieldTableCell*)cell;
#end
#interface FieldTableCell : UITableViewCell <UITextFieldDelegate>
#property (readonly, weak, nonatomic) AddressField* addressField;
#property (weak, nonatomic) id<FieldTableCellDelegate> delegate;
- (void)configureForField:(AddressField *)field;
- (void)startEditing;
#end
#implementation ViewController
{
NSArray * _fields; // I left to your discretion how to create fields and assign dependencies
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _fields.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FieldTableCell *cell = (FieldTableCell*)[tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
cell.delegate = self;
AddressField * field = _fields[indexPath.row];
field.indexPath = indexPath;
[cell configureForField:field];
return cell;
}
- (void)fieldCellDidEndEditing:(FieldTableCell *)cell
{
typeof(self) __weak weakSelf = self;
[UIView animateWithDuration:0.25
animations:^{
[weakSelf.tableView scrollToRowAtIndexPath:cell.addressField.dependency.indexPath
atScrollPosition:UITableViewScrollPositionMiddle
animated:NO];
}
completion:^(BOOL finished) {
FieldTableCell* nextCell = (FieldTableCell*)[weakSelf.tableView cellForRowAtIndexPath:cell.addressField.dependency.indexPath];
[nextCell startEditing];
}];
}
#end
#implementation FieldTableCell
{
UITextField* _inputField;
}
- (void)configureForField:(AddressField *)field
{
_addressField = field;
_inputField.text = field.value;
_inputField.placeholder = field.title;
// do all other configurations...
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
if (textField.text.length > 0) {
_addressField.value = textField.text;
[_delegate fieldCellDidEndEditing:self];
}
}
- (void)startEditing
{
[_inputField becomeFirstResponder];
}
#end
use textFielShouldBeginEditing method of UITextFieldDelegate
Declaration
SWIFT
optional func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool
OBJECTIVE-C
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
example-
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
//do state button enabled task here
}
With a button:
-(IBAction) continueButton: (UIButton*) sender{
//check if the state textfield is not empty in order to proceed
if(![self.stateTextfield.text isEqualToString: #""]){
self.cityTextfield.enabled = YES;
}
}
Simple get around but not really clean.
UPDATE
Use a normal View Controller.
Drag a Container View into the View Controller to allow for the size of your tableview that captures data.
Delete the automatically generated View Controller and drag a Table View Controller onto the storyboard and embed it in the Container View (ctrl + drag and select the embed in option)
Set this table view to Static.
Drag a TableView (not TableViewController) into the the ViewController.
Ctrl + drag the from TableView to the View Controller icon and set datasource and delegate. This will allow for data to load into the tableview.
This should now solve any issues with loading data as the data will load into the dynamic tableview and the static tableview will be unaltered (if this is a viable option for you). This way you can connect your textfields to your view controller and access their properties.
If you need any help or this isn't a good solution let me know.
I'm having an issue with displaying cells in my UITableViewController, simply..nothing shows up when I go to test. Below is my code.
FormationViewController.m
#import <Foundation/Foundation.h>
#import "FormationViewController.h"
#interface FormationViewController ()
#end
#implementation FormationViewController
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [self.names count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Title"
forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"Title"];
}
NSString *name = _names[indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%#", name];
return cell;
}
- (void) tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = #"Formation View";
self.tabBarItem.image = [UIImage imageNamed:#"tab_icon_formation"];
self.names = #[#"John Doe", #"Lee Harvey Oswald", #"Pat Buchanan", #"Angry Orchard",
#"Sierra Nevad", #"Jeff Bridges", #"John McClain", #"Lucy Genero"];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"The length of names is %lu", self.names.count);
}
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
self.formationVC.frame = CGRectMake(
0,
self.topLayoutGuide.length,
CGRectGetWidth(self.view.frame),
CGRectGetHeight(self.view.frame)
- self.topLayoutGuide.length
- self.bottomLayoutGuide.length
);
}
- (void)loadView {
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor whiteColor];
self.formationVC = [[UIView alloc] init];
self.formationVC.backgroundColor = [UIColor whiteColor];
[view addSubview:self.formationVC];
self.view = view;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
#end
And my FormationViewController.h
#import <UIKit/UIKit.h>
#interface FormationViewController : UITableViewController
#property (strong, nonatomic) UIView *formationVC;
#property (strong, nonatomic) NSArray *names;
#end
I'm also not sure if I'm putting some of these lines of code in the right methods.
I also think that my problem might be lying in the tableView:cellForRowAtIndexPath: method. I'm not absolutely sure I'm implementing that 100% correctly.
If anyone can help me find out what I'm doing wrong please let me know. This is my first Obj-C/iOS project I'm working on too so please be gentle! Thank you!
Well, I tried your code , using no xibs and faced the same problem.
Then I changed 2 things
removed LoadView.
moved self.names intialization from initWithNibName to viewDidLoad
added
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Title"];
[self.tableView reloadData];
to viewDidload
And it worked
I think you' re never stop in (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil ... if you instantiate your view controller from a storyboard, you need to implement initWithCoder, or just put your names initialization in viewDidLoad.
As you are probably using Storyboard, check these steps:
1) Storyboard - select your table view controller and in Identity Inspector make sure you have it's class set to your FormationVC.
2) Storyboard - select table view inside the controller and select it's first cell (suggesting you use Prototype Cells). Make sure it's style is set to Basic and set it's identifier for example to "BasicCell".
3) Go to your code and use this:
FormationVC.h
#import <UIKit/UIKit.h>
#interface FormationVC : UITableViewController
#end
FormationVC.m
#import "FormationVC.h"
#interface FormationVC ()
#property (strong, nonatomic) NSArray *names;
#end
#implementation FormationVC
#pragma mark - View Lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
// you must not forget to call your custom init method once the view is loaded
[self setupView];
}
- (void)setupView {
// set title of VC
self.title = #"Formation View";
// create array of names
_names = #[#"John Doe", #"Lee Harvey Oswald", #"Pat Buchanan", #"Angry Orchard",
#"Sierra Nevad", #"Jeff Bridges", #"John McClain", #"Lucy Genero"];
// log number of names in names array
NSLog(#"The length of names is %lu", _names.count);
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_names count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"BasicCell" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:#"%#", _names[indexPath.row]];
return cell;
}
#end
Problem IS there :-
#property (strong, nonatomic) NSArray *names;
change NSArrayTo NSMutableArray
in.h
EX:- #property (nonatomic , retain) NSMutableArray *names
and in.m
names = [[NSMutableArray alloc] init];
and then alloc init your Array and then put value its work .
I have a view controller with a static cell named 'Make' I have two controllers one called "AddCarTableViewController" and "MakeTableViewController" when you click on the static cell named 'Make' it presents the make table view controller where you can select the make, then pops the view controller and am trying to store the selected value in the detailTextLabel of the static cell. here is my code for all the controllers.
The problem I'm having is once I select the make everything happens as it should I even log the selected item and it saves it after popping the view controller, but I can't figure out how to implement selected item into the detailTextLabel. Any help will be much appreciated!
"MakeTableViewController.h"
#import <UIKit/UIKit.h>
#import "AddCarTableViewController.h"
#protocol CarMakeDelegate <NSObject>
- (void)updateCarMake:(NSString *)updateMake;
#end
#interface MakeTableViewController : UITableViewController
#property (nonatomic, strong) NSArray *carMakes;
#property (nonatomic, weak) id <CarMakeDelegate> delegate;
#end
MakeTableViewController.m
#import "MakeTableViewController.h"
#interface MakeTableViewController ()
#end
#implementation MakeTableViewController {
NSIndexPath *oldIndexPath;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.carMakes = [[NSArray alloc] initWithObjects:#"Acura", #"Aston Martin", nil];
}
- (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 [self.carMakes 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.textLabel.text = [self.carMakes objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:NO];
oldIndexPath = indexPath;
NSString *addMake = self.carMakes[indexPath.row];
[self.delegate updateCarMake:addMake];
NSLog(#"%#", addMake );
[[self navigationController] popViewControllerAnimated:YES];
}
#end
AddCarTableViewController.h
#import <UIKit/UIKit.h>
#import "MakeTableViewController.h"
#interface AddCarTableViewController : UITableViewController
#property (strong, nonatomic) NSString *makeName;
#property (weak, nonatomic) IBOutlet UITableViewCell *makeCell;
#end
AddCarTableViewController.m
#import "AddCarTableViewController.h"
#interface AddCarTableViewController ()
#end
#implementation AddCarTableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
#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 4;
}
-(void)updateCarMake:(NSString *)updateMake {
self.makeCell.detailTextLabel.text = updateMake;
}
#end
You don't need to use delegate in this case. Just update the underlying data model. and call
[tableview reloadData];
When the makeViewController is popped.
In the AddCarVC's cellForRowAtIndex, add another line to check if current indexPath corresponds to Make cell and if it does update the detailLabel text.
I Have a button within a uitableview cell -
I have set it up to trigger a fmethod when clicked - (the function displays messages and resets the message count).
my code for this method is as follows -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Define Custom Cells
static NSString *CellCountI =#"CellCount";
UITableViewCell *cell;
feedData *f = [self.HpFeedArray objectAtIndex:indexPath.section];
//Comparison Strings
NSString *count = #"Count";
//If statement Cell Filters
//If Count Cell
if ([f.FeedGroup isEqualToString:count]) {
cell = [tableView dequeueReusableCellWithIdentifier:CellCountI forIndexPath:indexPath];
HP_Header_TableViewCell *hpTC = (HP_Header_TableViewCell *)cell;
hpTC.buttonPressedSelector = #selector(buttonImpMsg);
hpTC.buttonPressedTarget = self;
[hpTC.msgsBtn setTitle: f.FeedTitle forState: UIControlStateNormal];
return hpTC;
}
}
The buttonImpMsg method is as follows -
- (void)buttonImpMsg
{
NSLog(#"Back Button Pressed!");
[self removeBtn];
}
I would like to hide the button when clicked - but I'm not sure how to reference it from the buttonImpMsg method?
Pass the sender to the selector:-
- (void)buttonImpMsg:(id)sender {
[sender removeFromSuperview];
}
You could implement the delegate pattern, IMHO, it's the most proper way.
i think , better will be to make it hidden, if you want to again. – #pawan
I would also hide the button rather than remove it.
Try this implementation to hide the button, you can also do the same thing to hide this one after.
TableViewCell.h:
#import "TableViewCell.h"
#implementation TableViewCell
//.... Connect your action or set selector to this method:
- (IBAction)hideButton:(id)sender
{
UIButton *button = (UIButton *) sender;
// hide the button by using the setter
button.hidden = YES;
//.... Check if the delegate method has been implemented
if ([_delegate respondsToSelector:#selector(hideButton)]) {
[_delegate hideButton];
}
}
#end
TableViewCell.h
//... Declare the delegate:
#protocol CellDelegate <NSObject>
- (void)hideButton;
#end
#interface TableViewCell : UITableViewCell
//... Add a delegate property:
#property (strong, nonatomic) id <CellDelegate> delegate;
#end
ViewController.m:
//... set self a the delegate of your cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//...
cell.delete = self;
return cell;
}
ViewController.m:
//...
#interface ViewController () <CellDelegate>
//...
//... Implement the delegate method if you need to do stuff on the controller side
- (void)hideButton
{
//do stuff here if needed
}