I have a tableviewcontroller with a uinavigation bar that has a barbuttonitem, called editBarButton. When editBarButton is pressed I want my tableview to be updated with a new button in each of the cells that says 'Edit'. What is the correct way to implement this?
- (void)onEditBarButtonPressed{
//TODO: update cells
}
You have to overwrite the accessoryView attribute in your UITableViewCell with your Edit button:
Create a custom button to overwrite the current accesoryView:
- (UIButton *) makeDetailDisclosureButton
{
UIButton * button = [UIButton yourEditButton];
[button addTarget: self
action: #selector(accessoryButtonTapped:withEvent:)
forControlEvents: UIControlEventTouchUpInside];
return ( button );
}
Then the button will call this routine when it's done, which then feeds the standard UITableViewDelegate routine for accessory buttons:
- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{
NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: self.tableView]];
if ( indexPath == nil )
return;
[self.tableView.delegate tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
You can see a similar question here: Using a custom image for a UITableViewCell's accessoryView and having it respond to UITableViewDelegate
I found a solution to my problem.
You should add a object level BOOL flag called editPressed.
It should be set to NO in viewDidLoad.
When making each cell, add a button to each and set it to hidden if need be:
[button setHidden:!editPressed];
It is important to use the flag so that when new cells are made they will keep the buttons hidden if they should be or visible otherwise.
Then have a object level NSMutableArray * of the buttons in the view controller and add each button to it:
[buttons addObject:button];
When you want to show each button, just change the hidden state:
editPressed = YES;
for(int i = 0; i != [butttons count]; i++){
[[buttons objectAtIndex:i] setHidden:!editPressed];
}
When you want to hide each button, once again, change the hidden state:
editPressed = NO;
for(int i = 0; i != [butttons count]; i++){
[[buttons objectAtIndex:i] setHidden:!editPressed];
}
Related
I am new to IOS development. I am working on an app in which I have few rows and a button in front of each row. In the cellForRowAtIndexPath I have created a function called buttonPressed() and in that function I want to get the data only corresponding to the button I click. Can you help me with this?
Here's what I am doing.
-(void) buttonPressed: (id) sender withEvent: (UIEvent *) event
{
UITouch *touch= [[event allTouched] anyObject];
CGPoint location = [touch locationInView: self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
trackedUser = [searchResult obectAtIndex:indexPath.row];
}
trackedUser is the object of a class which contains the details of a user like his name, id etc. And SearchResult is an array which displays the list of usernames (on searching in the search bar) in the table view controller.
Modify your cellForRowAtIndexPath-Adding button to cell code like below
UIButton *yourButton = [[UIButton alloc] initWithtarget:..] //creating UIButton with frame and target method
yourButton.tag= indexPath.row;
[cell addSubview:yourButton];
[yourButton release];
Then modify your buttonPressed method as below
-(void) buttonPressed: (id) sender withEvent: (UIEvent *) event
{
UIButton *myBtn = (UIButton *)sender;
trackedUser = [searchResult obectAtIndex:myBtn.tag];
}
//Instead of using Touch Handlers, you can make it more simple!!
In cellForRowAtIndexPath datasource add tags to UIButton like yourButton.tag = indexPath.row;
-(void) buttonPressed: (UIButton *) sender
{
NSLog(#"The row %d button was pressed",sender.tag);
//To get data, simply pass sender.tag as index in your NSArray or WhatEver you're using for storing data.
}
When you are creating button then set tag to button.
btn.tag= indexPath.row;
and when your button is press then access button with tag value
-(void) buttonPressed: (UIButton *) sender
{
UIButton *btn = (UIButton*)sender;
switch (btn.tag) {
case 0:
//Thing you want to perform
break;
default:
break;
}
}
I am trying to create a UITableView with a custom UIButton in each table cell. I implemented like this..
#implementation CouponDetailsCustomTableViewCell
...............
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
[self setBackgroundColor:[UIColor whiteColor]];
CGRect frame = self.contentView.frame;
self.radioButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.radioButton setImage:[UIImage imageNamed:#"radio_blank.png"] forState:UIControlStateNormal];
[self.radioButton setImage:[UIImage imageNamed:#"radio_selected"] forState:UIControlStateSelected];
[self.radioButton setFrame:CGRectMake(16, 10, 29, 29)];
[self.radioButton addTarget:nil action:#selector(radioButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:radioButton];
}
#end
and UITableView Delegate as......
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *COUPON_CELL_ID = #"CouponCell" ;
CouponDetailsCustomTableViewCell * couponCell = (CouponDetailsCustomTableViewCell *) [tableView dequeueReusableCellWithIdentifier:COUPON_CELL_ID];
if (couponCell == nil) {
couponCell = [[[CouponDetailsCustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:COUPON_CELL_ID] autorelease];
couponCell.selectionStyle = UITableViewCellSelectionStyleNone;
}
[couponCell.radioButton setSelected:NO];
return couponCell;
}
and the radioButtonPressed method is
-(void)radioButtonPressed:(id) sender
{
[sender setSelected:YES];
}
Now i run the program and a custom UIButton is shown in every table row . If i click on a button it gets selected (shows the radio_selected.png).
The problem arises when i scroll down the table (i am showing only 4 rows of the table in the window) . When i scroll up again..what i see is the clicked button is showing the radio_blank.png.
I am new in iPhone development. i dont know why is this happening. The most i can guess is the button property is changing .. setSelected:NO.
Someone please give me suggestions to fix this problem.
Thank you.
When you scroll your UITableView, hidden cells are not rendered anymore and might be reused for cells that are becoming visible. If a new cell becomes visible, tableView:cellForRowAtIndexPath: gets called.
The problem is that you're setting the selected state there:
[couponCell.radioButton setSelected:NO];
Therefore, whenever you scroll your cell out of the visible area and back again, it gets reset to selected = NO.
I suggest you create a NSMutableDictionary where you store the selection state of each row/NSIndexPath, which you then re-apply in tableView:cellForRowAtIndexPath:.
replace [couponCell.radioButton setSelected:NO]; in tableView:cellForRowAtIndexPath: with code that sets the selected property depending on a state from your dataSource.
something along those lines:
/* get the button state from your data source */
FancyCouponObject *coupon = [self.coupons objectAtIndex:indexPath.row];
BOOL buttonState = coupon.buttonState;
[couponCell.radioButton setSelected:buttonState];
The cells of a tableView are reused when they are moved off screen. You can't save state in them.
problem is when you scroll the table at that time your cellForRowAtIndexPath: delegate method called for every row... so here when its called at time your setSelected Method call with NO argument like bellow...
[couponCell.radioButton setSelected:NO];
so when you scroll table at time your setSelected method call and your button turn with radio_blank.png
...
:)
-(void)radioButtonPressed:(id) sender
{
[sender setSelected:YES];
}
in this method you are setting button as selected and for selected button you have set the radio_blank.png image
I have a UITableView with custom views for section headers. I added a UITapGestureRecognizer to the customer sections header views to detect when someone has tapped on a section header.
How do I figure out which section the section headers belong to?
Thanks in advance.
The easiest way is to designate a property on your section header view class to hold the section index, then assign the index to that property in -tableView:viewForHeaderInSection: like this:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// CustomHeaderView *headerView = ...
headerView.section = section;
// ...
return headerView;
}
Then have the gesture callback look at that property.
The action method that you are providing must have the following signature :
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer;
And a gestureRecognizer have the following properties :
Getting the Recognizer’s State and View
state property
view property
enabled property
So basically you can ask for the view that it is attached to and interrogate that view.
in the viewDidLoad section insert your gestureRecognizer:
- (void)viewDidLoad
{
(...)
UITapGestureRecognizer* doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(doubleTapTable:)];
doubleTap.numberOfTapsRequired = 2;
doubleTap.numberOfTouchesRequired = 1;
[self.yourTable addGestureRecognizer:doubleTap];
(...)
}
If you only want to detect single tap change doubleTap.numberOfTapsRequired to 1.
Then add the following method. This will check if the tapped point is inside section header:
-(void)doubleTapTable:(UISwipeGestureRecognizer*)tap
{
if (UIGestureRecognizerStateEnded == tap.state)
{
CGPoint p = [tap locationInView:tap.view];
NSIndexPath* indexPath = [yourTable indexPathForRowAtPoint:p];
if(indexPath){ // user taped a cell
// whatever you want to do if user taped cell
} else { // otherwise check if section header was clicked
NSUInteger i;
for(i=0;i<[yourTable numberOfSections];i++) {
CGRect headerViewRect = [yourTable rectForHeaderInSection:i];
BOOL isInside = CGRectContainsPoint (headerViewRect,
p);
if(isInside) {
// handle Header View Selection
break;
}
}
}
}
}
A bit late to the party here, but this can be a difficult problem to solve, especially if (as #klyngbaek mentions in the comments), you are adding/removing sections. Changing a tag or custom index property on the header UIView by reloading entire sections can result in ugly animations.
Try this as a callback method for the gesture recognizer that's attached to each header UIView (admittedly hackey):
- (void)headerTapped:(UITapGestureRecognizer *)sender{
NSInteger section = 0;
for(int counter = 0; counter < [self.tableViewOfInterest numberOfSections]; counter++){
if([[self.tableViewOfInterest headerViewForSection:counter] frame].origin.y == sender.view.frame.origin.y){
section = counter;
break;
}
}
}
Basically, when asking a UITableView for each section header, it returns an instance of the header with the frame set to the header's position in the table. Comparing this with the frame of the UITapGestureRecognizer's view property will result in a match at some point (no pun intended)!
You can add button to header and set tag to button something like this:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:
(NSInteger)section {
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.height, tableView.frame.size.width)];
UIButton *button = [[UIButton alloc] initWithFrame:headerView.frame];
button.tag = section;
[button addTarget:self action:#selector(detectSection:) forControlEvents:UIControlEventTouchUpInside];
[headerView addSubView:button];
return headerView;
}
-(void)detectSection:(UIButton *)sender {
switch(sender.tag) {
//your code
}
}
when i press the new button i need to add a textfield on last row of tableview.
can any one explain the flow.
Thanks in advance.
Just i tried this scenario.
Create a one Boolean variable like this
BOOL newButtonPress = NO;
then fallow the below code
-(IBAction)newButtonClicked:(id)sender{
if (self.newButtonPress == NO) {
//if new button press then newbuttpress is yes and reload the tableview
self.newButtonPress = YES;
[self .reloadTableview reloadData];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if(self.newButtonPress == YES)//creating noOfRows when newbutton pressed
{
return [self.itemNames count]+1;
}
else {
return [self.itemNames count];
}
}
Then add the below code into the cellForRowAtIndexPath method
//when new button is pressed adding new cell
if (self.newButtonPress == YES) {
if([self.itemNames count] == [indexPath row]){
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//creating the textfield if new button is pressed
UITextField *extraField = [[UITextField alloc] initWithFrame:CGRectMake(80, 6, 100, 30)];
extraField.borderStyle = UITextBorderStyleNone;
extraField.textAlignment = UITextAlignmentCenter;
[extraField becomeFirstResponder];
[extraField setDelegate:self];
[cell addSubview:extraField];
[extraField release];
}
}
If you just want the text field to appear at the end of the table, why not consider using UITableview's tableFooterView property?
In that case you don't have to ensure that you return the UITextField in your delegate methods.
You should nearly be able to drag drop a new UITextField in your Tableview if you are using InterfaceBuilder or XCode 4.
I am very new to iphone coding,i want to share my thoughts. If that is wrong please ignore.
In cellForRowAtIndexPath method u need to set a textfield in
if(indexPath.row==numberOfRows-1) condition.
In button pressed method u can set textField.hidden=NO and in viewdidload textField.hidden=YES.
I have implemented the accessory view of a UITableViewCell as a button, in the
button's selector method i have the following code
- (UIButton *) makeDetailDisclosureButton
{
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage* image = [UIImage imageNamed:#"custom.png"];
[button setImage:image forState:UIControlStateNormal];
button.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
[button addTarget: self
action: #selector(accessoryButtonTapped:withEvent:)
forControlEvents: UIControlEventTouchUpInside];
return ( button );
}
- (void) accessoryButtonTapped: (UIControl *)button withEvent:(UIEvent *) event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
if (indexPath != nil)
{
[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
}
However sometimes the wrong row is being selected, ie if I tap on row 0 in the table i get
row = 1 actually being selected. The code above is quite well known as a solution for
a custom accessory view but it is proving unreliable. Is there something else i need to do here?
Try this,
- (void) accessoryButtonTapped: (UIControl *)button withEvent:(UIEvent *) event
{
UITableViewCell *cell = (UITableViewCell*)button.superview.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
[self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
}
The idea here is pretty basic. Button's superview should give me cell.contentView and it's superview is the cell. There is lovely helper method indexPathForCell: which will give us the index path which we can use to pass to the delegate method.
Nothing wrong seen in your code but you can refer this tutorial for reference.
Difference I see in your code and in tutorial is
- (void) accessoryButtonTapped: (UIControl *)button withEvent:(UIEvent *) event //Your event
- (void)checkButtonTapped:(id)sender event:(id)event //In tutorial.
This does not make difference but still just a thought.
Hope it helps.
What do you have at tableView:accessoryButtonTappedForRowWithIndexPath: method?
Anyhow, I wouldn't mess with the touches to get the index path.
Instead I'd tag the button with the [indexPath row] and then pass the tag to the other method.
I had a similar problem: The index path row in tableView:accessoryButtonTappedForRowWithIndexPath: was consistently wrong for -- in my case -- every 5th row of the table view.
e.g., tapping the Detail Disclosure button for row 4 correctly gave me indexPath.row = 3; but tapping row 5 also gave me indexPath.row = 3.
My mistake related to having set incompatible row heights for my custom UITableViewCell.
i.e., I set the custom row height to 56 in the UITableViewCell's Size Inspector, but I forgot that I earlier had set the row height programmatically in tableView:heightForRowAtIndexPath: as a multiple of tableView.rowHeight. The default tableView.rowHeight (editable in the UITableView's Size Inspector) is 44, and that 'clash' apparently caused the problem.
I resolved my problem by setting the row height fields to 56 in the Size Inspectors of both the UITableView & the UITableViewCell and commenting out the tableView:heightForRowAtIndexPath: method.