Group UIButtons by UITableViewCell - objective-c

I have a UITableView with two cells that have two buttons in them. The cells need to be independent of one another. Both Button1's will be selected by default. I need to be able to toggle the buttons in the same cell without affecting the other cell. For example, if I click on Button2 in Option2, Button1 will be deselected in the same cell while Option3's buttons remain unaffected. The code I have to create the buttons within the UITableView is below. The selector would toggle the buttons. And each cell would execute a different method based on which button is selected. How can I group the buttons based on the cell that they are located in?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *menuId = #"OptionsMenu";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:menuId];
if (cell == nil)
cell = AUTO_RELEASE([[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:menuId]);
cell.textLabel.text = [self.options objectAtIndex:indexPath.row];
if ([cell.textLabel.text isEqualToString:#"Option2"] || [cell.textLabel.text isEqualToString:#"Option3"]) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(setState:) forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Button1" forState:UIControlStateNormal];
button.tag = indexPath.row;
button.frame = CGRectMake(200.0f, 5.0f, 80.0f, 30.0f);
button.layer.borderWidth = 1.0f;
button.layer.cornerRadius = 4.0f;
button.layer.borderColor = [[UIColor grayColor] CGColor];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button2 addTarget:self action:#selector(setState:) forControlEvents:UIControlEventTouchDown];
[button2 setTitle:#"Button2" forState:UIControlStateNormal];
button2.tag = indexPath.row;
button2.frame = CGRectMake(300.0f, 5.0f, 80.0f, 30.0f);
button2.layer.borderWidth = 1.0f;
button2.layer.cornerRadius = 4.0f;
button2.layer.borderColor = [[UIColor grayColor] CGColor];
[cell addSubview:button];
[cell addSubview:button2];
}
return cell;
}

You want to make the cell the target of the control actions, not the table view. Then you can make the tableview a delegate of the cell. When the cell receives the setState: message, you have the cell tell the tableview via the delegate. You pass a pointer to the cell as part of the delegate message, and now the tableview knows what item to update in the model via indexPathForCell:.

Related

Button click method is not working in collection view

I am creating a camera app. I am showing captured pictures in collection view. I placed a button to delete the particular picture. While running I am able to see the button to delete, but if I click the button it is not performing any action.
-(UICollectionViewCell *)collectionView:(UICollectionView *)
collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell *Cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
Cell.self.image_View.image=[self.imageArray objectAtIndex:indexPath.row];
UIButton *deleteButton = [[UIButton alloc]init];
deleteButton.frame = CGRectMake(80, 0, 20, 20);
//deleteButton.backgroundColor = [UIColor redColor];
[deleteButton setImage:[UIImage imageNamed:#"delete.png"] forState:UIControlStateNormal];
[deleteButton setTag:indexPath.row];
[deleteButton addTarget:self action:#selector(delete:) forControlEvents:UIControlEventTouchUpInside];
[Cell.self.image_View addSubview:deleteButton];
return Cell;
}
-(void) delete:(UIButton*)sender{
UIButton *btn = (UIButton *)sender;
[self.imageArray removeObjectAtIndex:btn.tag];
//reload your collectionview here
}
Can anyone help me?
i think you might be missing
[collectionView reloadData]
-(void) delete:(UIButton*)sender{
UIButton *btn = (UIButton *)sender;
[self.imageArray removeObjectAtIndex:btn.tag];
[collectionView reloadData]
}

Table View Cell Button Not Responding with it index position

I have Custom Table View Cell In That I Have Two UIButton and One Text Field Named As edit and cancel and one textField. When I Click on edit at same time TextFeild Interaction is Enabled And Cancel Button Image Should Change. Its Working Fine For Me!!
But When I am Clicking On Edit Button Another Cells Cancel bitton Image id Changed Automatically! I know that this happening because I'm reusing the cell!! But I'm not able to find a solution...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
simpleTableIdentifier = #"MenuNameCell";
cell = (MenuNameCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (!cell) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MenuNameCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
NSLog(#"---------new cell agin");
}
else
{
for (UIView *view in [cell.contentView subviews])
[view removeFromSuperview];
NSLog(#"---------older use");
// _checkButton = (UIButton *)[cell.contentView viewWithTag:indexPath.row];
// _cancelButton = (UIButton *)[cell.contentView viewWithTag:indexPath.row];
}
// Creating Label Menu Name
_nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 11, 82, 21)];
_nameLabel.backgroundColor = [UIColor clearColor];
_nameLabel.text = [_hotel._orderedMenus objectAtIndex:indexPath.row];
// Creating Label Menu Cost
_amountMenu = [[UILabel alloc] initWithFrame:CGRectMake(167, 13, 44, 21)];
_amountMenu.backgroundColor = [UIColor clearColor];
_amountMenu.text = [[_hotel._menuPrices objectAtIndex:indexPath.row] stringValue];
// Creating Text Field For Order Quantity
_textFieldQuantity = [[UITextField alloc] initWithFrame:CGRectMake(125,14,42,21)];
_textFieldQuantity.userInteractionEnabled = NO;
_textFieldQuantity.text = [[_hotel._selectedQuantity objectAtIndex:indexPath.row] stringValue];
// Creating Button For Check Order
_checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_checkButton setFrame:CGRectMake(232, 13, 25, 28)];
[_checkButton setBackgroundImage:[UIImage imageNamed:#"edit.png"]forState:UIControlStateNormal];
[_checkButton addTarget:self action:#selector(editQuantity:) forControlEvents:UIControlEventTouchUpInside];
[_checkButton setTag:indexPath.row];
// Creating Button For CANCEL Order
_cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_cancelButton setFrame:CGRectMake(265, 13, 25, 28)];
[_cancelButton setBackgroundImage:[UIImage imageNamed:#"cancel.png"] forState:UIControlStateNormal];
[_cancelButton addTarget:self action:#selector(cancelOreder:) forControlEvents:UIControlEventTouchUpInside];
[_cancelButton setTag:indexPath.row];
// Adding All To Call Content View
[cell.contentView addSubview:_nameLabel];
[cell.contentView addSubview:_amountMenu];
[cell.contentView addSubview:_textFieldQuantity];
[cell.contentView addSubview:_checkButton];
[cell.contentView addSubview:_cancelButton];
return cell;
}
Edit:
-(void)editQuantity:(id)sender
{
_textFieldQuantity.userInteractionEnabled = YES;
button = (UIButton *)sender;
row = button.tag;
NSLog(#"Check Button index is %d",row);
UIImage *buttonImage = [UIImage imageNamed:#"edit_over.png"];
[_checkButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
UIImage *buttonImageCancel = [UIImage imageNamed:#"check.png"];
[_cancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
_cancelButton.tag = 0;
}
-(void)cancelOreder:(id)sender{
button = (UIButton *)sender;
row = button.tag;
NSLog(#"The Row Selected iS At Cancel Order ISSSS----%d", row);
if (_cancelButton.tag == 0){
_textFieldQuantity.userInteractionEnabled = NO;
UIImage *buttonImageCancel = [UIImage imageNamed:#"check_over.png"];
[_cancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
UIImage *buttonImageCancel1 = [UIImage imageNamed:#"cancel.png"];
[_cancelButton setBackgroundImage:buttonImageCancel1 forState:UIControlStateNormal];
UIImage *buttonImage = [UIImage imageNamed:#"edit.png"];
[_checkButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
_cancelButton.tag = 1;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iHomeDelivery" message:#"Do You Want To Cancel the Order" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
Your problem is that _textFieldQuantity (and the others) is an instance variable. When editQuantity: and cancelOreder: are called the instance varialbe still has the same value that was set last time when adding a cell within cellForRowAtIndexPath: .
What could you do to fix it?
1st:
You could set the row in the tag of the button. Then, when the button is tapped on and the action is invoced get the tag and fetch the cell (you can call the table's cellForRowAtIndexPath method to get it. That is different from the delegate method that you implement) and then find the appropriate textField.
2nd:
A bit more work but probably smarter could be to implment a subclass of your table cell. Move the action methods to that very cell class. Doing so each button's action refers to an individual object wich is then the cell class and not the view controller. The cell class can have its own textField instance variables. It shoud even provide properties to the textField and other UIItems so that you can set their values in cellForRowAtIndexPath.
I would suggest the first solution as a quick starter. But for future use I strongly suggest to go the second way. That way will help you in similar situations in the future.

Button on UITableViewCell

i can create a button in tableview and i have a offers and in that offers i have products so i can generate all products as per offer in one table so i have a button to add cart when user add to cart it will show remove button its ok when i won't go to other view but when im came back it shows again add button so how can i get remove button after add and after came to this view please help me out thankyou
Translation
I want to create a button in a tableview. The button initial state should be 'Add to cart' and when the user clicks the button I want it to change to 'Remove'.
Translation
UIButton *btn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
btn.frame = CGRectMake(230, 25, 73, 40) ;
btn.tag = indexPath.row+1;
btn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
for (int i=0;i<[[[productsArray valueForKey:#"product"] valueForKey:#"productId"] count]; i++)
{
BOOL status=FALSE;
for (int j=0; j<[[appDelegate AddingCartArray] count]; j++)
{
NSString *pstr=[NSString stringWithFormat:#"%#",[[[productsArray valueForKey:#"product"] valueForKey:#"productId"] objectAtIndex:i]];
NSLog(#"pstr %#",pstr);
NSString *cstr=[NSString stringWithFormat:#"%#",[[[appDelegate AddingCartArray]valueForKey:#"productId"] objectAtIndex:j]];
NSLog(#"cstr %#",cstr);
if([[[productsArray valueForKey:#"product"] valueForKey:#"productId"] objectAtIndex:i] == [[[appDelegate AddingCartArray]valueForKey:#"productId"] objectAtIndex:j])
{
status =TRUE;
}
}
if(status)
{
[btn setBackgroundImage:[UIImage imageNamed:#"RemovetoCart.png"] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(Remove:) forControlEvents:UIControlEventTouchUpInside];
}
else {
[btn setBackgroundImage:[UIImage imageNamed:#"adtoCart.png"] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(addCartClicked:) forControlEvents:UIControlEventTouchUpInside];
}
}
[cell addSubview:btn];
[btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[btn release];
You should use method delegated from UITableView to add objects on UITableViewCell:
- (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] autorelease];
// your button code generation here and assigning touch event to it
[cell.contentView addSubview:btn]
return cell;
}
after that you can create method which receives touchUpInside event and sets to sender (UIButton *) nesessary properties such as color or text.
btw: you shouldn't use absolute values in frame generating. Use cell.contentView.frame property for creating button frame CGRect .

Cocoa-Touch – UITableView setEditing will not show specific cells

I've been struggling with this problem for a good 2 hours now and I can not get it to work.
I have a view controller with a table view on it with a list of items. When the user touches the EDIT button in the navigation bar the table view should enter "edit mode" and under the list of items one new cell should appear that should only be visible when it is in "edit mode".
So in my -tableView:cellForRowAtIndexPath: method I'm checking if (tableView.isEditing) to setup the cell. I've tried overriding -setEditing:animated: and doing [tableView reloadData] calls but I just can't get it to work.
This is what my -setEditing:animated: look like:
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
[self.groupDetailsTableView setEditing:editing animated:animated];
}
My -tableView:cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
if (tableView.isEditing) {
// Other tableview code has been omitted
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:nil];
// Set the background view of the cell to be transparent
UIView *backView = [[UIView alloc] initWithFrame:CGRectZero];
backView.backgroundColor = [UIColor clearColor];
cell.backgroundView = backView;
UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
[deleteButton setFrame:[cell.contentView frame]];
[deleteButton setFrame:CGRectMake(0, 0, cell.bounds.size.width-20, 44)];
[deleteButton setBackgroundImage:[UIImage imageNamed:#"redbutton.png"] forState:UIControlStateNormal];
[deleteButton setTitle:#"Delete Group" forState:UIControlStateNormal];
[deleteButton.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
[deleteButton.titleLabel setShadowColor:[UIColor lightGrayColor]];
[deleteButton.titleLabel setShadowOffset:CGSizeMake(0, -1)];
[deleteButton addTarget:self action:#selector(deleteGroup) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:deleteButton];
return cell;
}
}
And I'm calling [self setEditing:YES animated:YES]; from a method when the user touches the Edit button. I've also tried just calling [super setEditing:YES animated:YES]; and [self.groupDetailsTableView setEditing:YES animated:YES];
Found the answer myself at http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/ManageInsertDeleteRow/ManageInsertDeleteRow.html#//apple_ref/doc/uid/TP40007451-CH10-SW19
Apparently -tableView:cellForRowAtIndexPath: doesn't get called automatically when calling -setEditing:animated:
So to have a new cell "appear" I set the alpha to 0.0 and then 1.0 after calling setEditing...

How to create a UITableViewCell that contains a single UIButton taking up most of the cell's space?

I'm trying to create a UITableViewCell that contains a single big button.
I tried what seemed obvious, adding a UIButton to the cell's contentView, but it didn't work (the cell is displayed empty). What am I dong wrong?
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"startButtonCell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"startButtonCell"] autorelease];
UIButton *btn = [[UIButton alloc] initWithFrame:cell.contentView.bounds];
[cell.contentView addSubview:btn];
if (!self.task.isCompleted) {
btn.titleLabel.text = #"Start!";
}else{
btn.titleLabel.text = #"Continue!";
}
[btn release];
}
Try the following:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setFrame:cell.contentView.frame];
[btn setTitle:#"Button Title" forState:UIControlStateNormal];
[cell.contentView addSubview:btn];
I am by far no expert but I think the problem with your solution is that by default the button style of UIButton is UIButtonTypeCustom, which is invisible because it is not customized yet. If I change the code above from
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
to
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
I get get the same result you do. No Button visible. If you would like to use UIButtonTypeCustom you would have do do some customization. Adding a background image to your button for example.