UIButton click sender always go to selected option - ios

I have a UIButton click sender as below:-
-(IBAction)clipButtonClick:(UIButton *)sender
{
sender.selected = ! sender.selected;
if (sender.selected)
{
[btnClipCategory setImage:[UIImage imageNamed:#"imgClip_HL"] forState:UIControlStateSelected];
NSMutableArray* indexArray = [NSMutableArray array];
for (NSInteger i = 0; i < self.arySubCategory.count; i++)
{
[aryCheckCategoryList replaceObjectAtIndex:i withObject:#"YES"];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
[indexArray addObject:indexPath];
dispatch_async(dispatch_get_main_queue(), ^{
[self.rightTableView reloadData];
});
}
}
else
{
[btnClipCategory setImage:[UIImage imageNamed:#"imgClip"] forState:UIControlStateNormal];
NSMutableArray* indexArray = [NSMutableArray array];
for (NSInteger i = 0; i < self.arySubCategory.count; i++)
{
[aryCheckCategoryList replaceObjectAtIndex:i withObject:#"NO"];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
[indexArray addObject:indexPath];
dispatch_async(dispatch_get_main_queue(), ^{
[self.rightTableView reloadData];
});
}
}
}
When I clicked on the button, sender will always hit on selected option.
If i change the sender to code to sample code as below, my apps will working properly as expected. Any idea? Please help. Thank you.
-(IBAction)clipButtonClick:(UIButton *)sender
{
sender.selected = ! sender.selected;
if (sender.selected)
{
[btnClipCategory setImage:[UIImage imageNamed:#"imgClip_HL"] forState:UIControlStateSelected];
NSLog(#"Selected. Will Hit here");
}
else
{
[btnClipCategory setImage:[UIImage imageNamed:#"imgClip"] forState:UIControlStateNormal];
NSLog(#"Non Selected. Will Hit here");
}
}
Edited
I put my button under willDisplayHeaderView.
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
btnClipCategory = [UIButton buttonWithType:UIButtonTypeCustom];
[btnClipCategory setFrame:CGRectMake(header.frame.size.width - 45, header.frame.size.height * 0.2, ScreenW * 0.1, ScreenW * 0.1)];
[btnClipCategory addTarget:self action:#selector(clipButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[header addSubview:btnClipCategory];
}

When you call [self.rightTableView reloadData], all the content of the table view including sections headers gets reloaded, and tableView:willDisplayHeaderView:forSection: gets called for each visible section header. So your bntClipCategory gets recreated with default value of isSelected each time click action fires.
You don't reload rightTableView in your working code sample, that's why it works.
You should reconsider you approach. One of the options is to save isSelected state of buttons for each section in array and update btnClipCategory.isSelected accordingly before adding it to header view.

Related

How to select all uitableview cells on button click

I am making an app in which i am using buttons in the form of checkboxes in uitableview cell.i am changing images on that checkbox select and unselect state. now i want that when i click on another button then all the cells of table view will be select and image of all the checkboxes of cells will changed? how it can done below is my sample code
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.lblArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *tableviewidentifier = #"cell";
TablecellTableViewCell *cell= [self.tblvie dequeueReusableCellWithIdentifier:tableviewidentifier];
if(cell==nil)
{
cell = [[TablecellTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:tableviewidentifier];
}
cell.lblImage.layer.cornerRadius=3.0f;
cell.lblImage.layer.borderWidth=1.0f;
cell.backgroundColor=[UIColor colorWithRed:(245/255.0) green:(245/255.0) blue:(245/255.0) alpha:1];
if ([self.checkimageArray containsObject:[self.lblArray objectAtIndex:indexPath.row]])
{
[cell.buttonCheckbox setImage:[UIImage imageNamed:#"check_box_ok.png"]
forState:UIControlStateNormal];
}
else
{
[cell.buttonCheckbox setImage:[UIImage imageNamed:#"uncheck.png"]
forState:UIControlStateNormal];
}
cell.buttonCheckbox.tag=indexPath.row;
[cell.buttonCheckbox addTarget:self action:#selector(checkButton:) forControlEvents:UIControlEventTouchUpInside];
cell.lblText.text=[self.lblArray objectAtIndex:indexPath.row];
return cell;
}
-(IBAction)checkButton:(UIButton *)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tblvie];
NSIndexPath *indexPath = [self.tblvie indexPathForRowAtPoint:buttonPosition];
if ([self.checkimageArray containsObject:[self.lblArray objectAtIndex:indexPath.row]]) {
[self.checkimageArray removeObject:[self.lblArray objectAtIndex:indexPath.row]];
self.titleLabel.text=#"";
}
else {
[self.checkimageArray addObject:[self.lblArray objectAtIndex:indexPath.row]];
self.titleLabel.text=[self.lblArray objectAtIndex:sender.tag];
}
[self.tblvie reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation: UITableViewRowAnimationFade];
}
and here is my button in which i click then all the cells of tableview will select and images of all the cells will changed but it is not working
- (IBAction)selectbtns:(id)sender {
static NSString *tableviewidentifier = #"cell";
TablecellTableViewCell *cell= [self.tblvie dequeueReusableCellWithIdentifier:tableviewidentifier];
[cell.buttonCheckbox setImage:[UIImage imageNamed:#"check_box_ok.png"]
forState:UIControlStateNormal];
}
NSMutableArray *totalcheckmarkArray; //add on NSMutablearray in globally
- (void)viewDidLoad {
totalcheckmarkArray =[[NSMutableArray alloc]init];
for (int i=0; i<[self.lblArray count]; i++) // Number of Rows count
{
[self.totalcheckmarkArray addObject:#"NO"];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *tableviewidentifier = #"cell";
TablecellTableViewCell *cell= [self.tblvie dequeueReusableCellWithIdentifier:tableviewidentifier];
if(cell==nil)
{
cell = [[TablecellTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:tableviewidentifier];
}
cell.lblImage.layer.cornerRadius=3.0f;
cell.lblImage.layer.borderWidth=1.0f;
if(![[self.totalcheckmarkArray objectAtIndex:indexPath.row] isEqualToString:#"NO"])
{
[cell.buttonCheckbox setImage:[UIImage imageNamed:#"check_box_ok.png"] forState:UIControlStateNormal];
}
else if ([self.checkimageArray containsObject:[self.lblArray objectAtIndex:indexPath.row]])
{
[cell.buttonCheckbox setImage:[UIImage imageNamed:#"check_box_ok.png"] forState:UIControlStateNormal];
}
else
{
[cell.buttonCheckbox setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
}
cell.buttonCheckbox.tag=indexPath.row;
[cell.buttonCheckbox addTarget:self action:#selector(checkButton:) forControlEvents:UIControlEventTouchUpInside];
cell.lblText.text=[self.lblArray objectAtIndex:indexPath.row];
return cell;
}
selectAll Checkbox
- (IBAction)selectbtns:(id)sender {
for (int i=0; i<[self.lblArray count]; i++)
{
[totalcheckmarkArray replaceObjectAtIndex:i withObject:#"YES"];
}
[self.tblvie reloadData];
}
DeselectAll Checkbox
-(IBAction)deselectall_btnclick:(id)sender
{
for (int i=0; i<[self.lblArray count]; i++)
{
[totalcheckmarkArray replaceObjectAtIndex:i withObject:#"NO"];
}
[self.tblvie reloadData];
}
I can think of two possible solutions. If the following line works in cellForRowAtIndexPath:
if ([self.checkimageArray containsObject:[self.lblArray objectAtIndex:indexPath.row]]) {
[cell.buttonCheckbox setImage:[UIImage imageNamed:#"check_box_ok.png"] forState:UIControlStateNormal];
}
Then just add all the images to self.checkimageAray and then reload the table through [self.tblvie reloadData].
If there is a reason you don't want to reload the table, you could do the following, which will loop through all the cells in the table and execute the changes to each cell:
for (int section = 0; section < [self.tblvie numberOfSections]; section++) {
for (int row = 0; row < [self.tblvie numberOfRowsInSection:section]; row++) {
NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
TablecellTableViewCell *cell= [self.tblvie cellForRowAtIndexPath:cellPath];
[cell.buttonCheckbox setImage:[UIImage imageNamed:#"check_box_ok.png"]
forState:UIControlStateNormal];
}
}
I tend to iterate over every cell when I wish to make a change with an animation. If say you want to animate the checking of the box, the simplest way would be to place the animation block in the iteration of the cells.
If you wish to then unselect a cell, you could do the following:
for (int section = 0; section < [self.tblvie numberOfSections]; section++) {
for (int row = 0; row < [self.tblvie numberOfRowsInSection:section]; row++) {
NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:section];
TablecellTableViewCell *cell= [self.tblvie cellForRowAtIndexPath:cellPath];
[cell.buttonCheckbox setImage:[UIImage imageNamed:#"uncheck.png"]
forState:UIControlStateNormal];
}
}
Please note that this is not changing your checkimageArray. While the cells are being displayed as selected, all of the images are not in your checkimageArray, and of corse with my solution for unselecting the cell, the images will not be removed from the checkimageArray either.
I would suggest adding all the objects from self.lblArray to checkimageArray where you place the code to set the cells highlighted and remove all objects from checkimageArray when you deselect them all. An example of how to add all images to the array is show in the other answer bellow.
You can do .
- (IBAction)selectbtns:(id)sender
{
self.checkimageArray = [NSArray arrayWithArray:self.lblArray];
[self.tableView reloadData];
}

how to find button in cell subview

Good day!
Here is a problem: i've added a button in cell in my UITableView programmatically like this:
UIButton *button = [[UIButton alloc] initWithFrame:buttonFrame];
[button setImage:[UIImage imageNamed:#"Button_off_weather"] forState:UIControlStateNormal];
button.tag = indexPath.row;
[button addTarget:self action:#selector(buttonCityTapped:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview: button];
it works fine.
then i want to find it in table and switch off like this:
NSMutableArray *cells = [[NSMutableArray alloc] init];
for (NSInteger j = 0; j < [_tableView numberOfSections]; ++j)
{
for (NSInteger i = 0; i < [_tableView numberOfRowsInSection:j]; ++i)
{
[cells addObject:[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]];
for (UITableViewCell *cell in cells)
{
for (id theView in cell.subviews) {
if ([theView isKindOfClass:[UIButton class]]) {
[theView performSelector:#selector(buttonOff:)];
}
}
}
}
}
this does not work. is there any ideas?
Create a custom cell subclass with an #property making the button available. This is the correct approach to take.
Your current approach is currently and will in the future be error prone. Try not to rely on code which traverses view hierarchies, particularly if you don't have control over some parts of the view hierarchy (like the cell subviews).
use enumeration with [cell.contentView subviews]
for(UIView *view in [cell.contentView subviews])
{
if([view isKindOfClass:[UIButton class]])
{
[theView performSelector:#selector(buttonOff:)];
}
}
Check This: Works fine for me.
int sections = [self.tableView numberOfSections];
for (int i=0; i<sections; i++) {
//For the Custom cell
NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:i] ;
CellStar *cell =(CellStar *) [self.tableView cellForRowAtIndexPath:myIP];
UITextView *txtVi ;
NSArray *subviews = cell.contentView.subviews;
for(id element in subviews) {
if ([element isKindOfClass:[UITextView class]]){
NSLog(#"element is a UItextView\n");
txtVi = (UITextView *)element;
}
if([element isKindOfClass:[UIButton class]]){
UIButton *btn = (UIButton *) element;
NSLog(#"element is UIButton\n");
}
}
//[self.tableView reloadData];
}

Set button tag for different sections of UITableView

I list of contacts from Web Service and display it in contacts 'sectioned' tableView as seen in the screenshot.
Issue is I get same tag values for checkboxes of first row for section A as well as section S. I have sorted one array and displayed in the indexed table view. How to get different tag values depending on indexPath.row irrespective of number of sections displayed. Here's what I tried
In cellForRowAtIndexPath:
UIButton *checkBox;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(7, 8, 30, 30)];
}
else
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(15, 13, 30, 30)];
}
//int cnt = 0;
// for (int i = indexPath.section - 1; i > 0 ; i--)
// {
// cnt += [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:i]] count]; //arrayOfCharachters has char 'A' to 'Z'
// }
//checkBox.tag = cnt + indexPath.row;
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
[checkBox addTarget:self action:#selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
[checkBox setTag:indexPath.row];
[cell.contentView addSubview:checkBox];
return cell;
}
-(void)checkBoxClicked:(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableViewContact];
NSIndexPath *indexPath = [self.tableViewContact indexPathForRowAtPoint:buttonPosition];
UIButton *tappedButton = (UIButton*)sender;
NSLog(#"Tag number = %d", [sender tag]);
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"checkBox.png"]])
{
[sender setImage:[UIImage imageNamed: #"checkBoxMarked.png"] forState:UIControlStateNormal];
if(indexPath != Nil)
{
NSString *finalIntId = [mutableArrayOfIds objectAtIndex:indexPath.row]; // store check box ids in mutableArrayOfIds
NSLog(#"Tagged checked button id = %#", finalIntId);
[arrayOfIds addObject:finalIntId];
}
//NSString *finalIntId = [mutableArrayOfIds objectAtIndex:tappedButton.tag];
//NSString *finalIntId = [mutableArrayOfIds objectAtIndex:indexPath.row];
}
else
{
[sender setImage:[UIImage imageNamed:#"checkBox.png"]forState:UIControlStateNormal];
NSLog(#"UnChecked");
//[arrayOfIds removeObjectAtIndex:tappedButton.tag];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if ([arrayOfCharacters count] == 0)
{
return #"";
}
return [NSString stringWithFormat:#"%#", [arrayOfCharacters objectAtIndex:section]];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
NSArray *toBeReturned = [NSArray arrayWithArray:
[#"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#"
componentsSeparatedByString:#"|"]];
return toBeReturned;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
NSInteger count = 0;
for (NSString *character in arrayOfCharacters) {
if ([character isEqualToString:title]) {
return count;
}
count ++;
}
return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [arrayOfCharacters count];
//return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//return [mutableArray count];
return [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:section]] count];
}
you are setting the same tag value for all sections which have same row.
The indexPath has two properties, {section,row}.
Lets say section A has two rows,
for row1 -> indexPath.section=0, indexPath.row=0;
for row2-> indexPath.section=0, indexPath.row=1;
Lets say section S has two rows,
for row1 -> indexPath.section=1, indexPath.row=0;
for row2-> indexPath.section=1, indexPath.row=1;
So, for row1 of section A and row1 of section S, you are setting the same tag value which is 0.There is your problem.
Try setting tag value like below.
button.tag = indexPath.section*1000 +indexPath.row;
when retrieving the section and row,
NSInteger section = (button.tag)/1000;
NSInteger row = (button.tag)%1000;
Try this...
- (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];
}
UIButton *checkBox =[[UIButton alloc] initWithFrame:CGRectMake(280, 10, 50, 44)];
checkBox.backgroundColor =[UIColor orangeColor];
[checkBox addTarget:self action:#selector(checkBoxClicked:event:)forControlEvents:UIControlEventTouchUpInside];
[checkBox setTag:indexPath.row];
[cell.contentView addSubview:checkBox];
return cell;
}
- (void)checkBoxClicked:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tv]; //here tv is TableView Object
NSIndexPath *indexPath = [self.tv indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"value of indePath.section %d ,indexPath.row %d",indexPath.section,indexPath.row);
}
This is happening because you are assigning tag to buttons INDEPENDENT of sections.
Both of First Row of Sections A & S have row = 0. so Tag Assigned to their respective button is 0. You should assign them Keeping reference to your sections.
i would suggest to assign accessibility hint with comma separated form containing Section,Row.
And in your method
-(void)checkBoxClicked:(id)sender
{
//pick string from comma separated form. 1st is your section, 2nd is row.
}
second option is Do what ever your doing and implement your Button method like this.
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
if (indexPath != nil)
{
... indexpath.section is your section , index path.row is your row.
}
There is Third option as well.
in cellforRowAtIndexpath assign your Button a title
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
[btn setTitle:<#Your Row#> forState:UIControlStateDisabled];
[btn setTag<#Your Section#>];
so upon Receiving in your Button Method you can have both Section (Tag) and Row (Title for Disabled state).
-(void)checkBoxClicked:(id)sender { [button titleForState:UIControlStateDisabled]; // your Row
button.tag //your Section }
Try this!
Each section you may know the count of section right, then add count of individual row.
[[fieldTitlesList objectAtIndex:indexPath.section - 1] count] + indexPath.row
Where fieldTitlesList is the array of your sections.
I added the following code which solved my issue
NSInteger rowNumber = 0;
for(NSInteger i = 0; i < indexPath.section ; i++)
{
rowNumber += [self tableView:self.tableViewContact numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
[checkBox setTag:rowNumber]; //checkBox is UIButton in cellForRowAtIndexPath

Button Image Quality Collection View

I have a collection view where each cell contains 7 buttons, (created via code not storyboard).
They are sharp initially, however if I scroll up / down a few times the quality decreases.
The sharpness is restored when I change views and return.
Any ideas ?
Addit:
I am making the buttons like this, within a loop (can be 1 to 7 buttons)
- (UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"patientCell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
Patient *aPt = [self.fetchedResultsController objectAtIndexPath:indexPath];
PatientCVCell *ptCell = (PatientCVCell *) cell;
ptCell.ptName.text = aPt.name;
ptCell.ptRoom.text = aPt.room;
ptCell.ptRx.text = aPt.diagnosis;
int xPos = 20;
NSArray *daysForRx = aPt.ofList.listDays;
// loop through to add button for each day of Rx
for (int i = 0; i < [daysForRx count]; i++) {
// get the treatment day that == postition in array
for (Treatment *t in aPt.patientRx) {
if (t.day == daysForRx[i]) {
//NSLog(#"%i", xPos);
StatusButton *testButton = [StatusButton buttonWithType:UIButtonTypeCustom];
testButton.frame = CGRectMake(xPos, 110, 28, 28);
testButton.btnTreatment = t;
// match status of the RX to the correct button
if ([t.status intValue] == NotSeen) {
[testButton setImage:[UIImage imageNamed:#"toSee"] forState:UIControlStateNormal];
testButton.linkNumber = NotSeen;
}
else if ([t.status intValue] == SeenNotCharted) {
[testButton setImage:[UIImage imageNamed:#"seenNotCharted"] forState:UIControlStateNormal];
testButton.linkNumber = SeenNotCharted;
}
else if ([t.status intValue] == SeenCharted) {
[testButton setImage:[UIImage imageNamed:#"seenCharted"] forState:UIControlStateNormal];
testButton.linkNumber = SeenCharted;
}
else if ([t.status intValue] == NotSeeing) {
[testButton setImage:[UIImage imageNamed:#"notSeeing"] forState:UIControlStateNormal];
testButton.linkNumber = NotSeeing;
}
else if ([t.status intValue] == NotSeeingDC) {
[testButton setImage:[UIImage imageNamed:#"notSeeingDischarged"] forState:UIControlStateNormal];
testButton.linkNumber = NotSeeingDC;
}
[testButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:testButton];
xPos = xPos + 36;
}
}
}
return cell;
}
The image is correct size so no need to scale the image.
Occurs in simulator and on device.
After looking more closely, the inside of the images are sharp! So this issue has to do with the transparency for my circle shape of a button within a square button!
You are dequeuing a cell, then you add your buttons to the dequeued cell.
Those buttons never get removed. When you scroll up and down cells that go off screen are put on the dequeue queue. At this time they still have the buttons, then they are dequeued and you add more buttons. You have many buttons above each other, and that's why it looks blurry and your memory footprint gets bigger.
I would add the buttons from inside the cell. Save them in a array so you can remove them later. Then I would add a method to set the number of buttons you'll need. Like this:
// header
#property (strong, nonatomic) NSMutableArray *buttons;
// implementation
- (void)setNumberOfButtons:(NSInteger)numberOfButtons withTarget:(id)target selector:(SEL)selector {
// remove existing buttons from view
[self.buttons makeObjectsPerformSelector:#selector(removeFromSuperview)];
// "save" existing buttons in a reuse queue so you don't have to alloc init them again
NSMutableArray *reuseQueue = self.buttons;
self.buttons = [NSMutableArray arrayWithCapacity:numberOfButtons];
for (NSInteger i = 0; i < numberOfButtons; i++) {
UIButton *button = [reuseQueue lastObject];
if (button) {
[reuseQueue removeLastObject];
}
else {
button = [UIButton buttonWithType:UIButtonTypeCustom];
// you should always use the same target and selector for all your cells. otherwise this won't work.
[button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
}
[self.buttons addObject:button];
button.frame = ....
// don't set up images or titles. you'll do this from the collectionView dataSource method
}
}
you would then set the number of buttons in collectionView:cellForItemAtIndexPath: and configure each button according to your needs. something along those lines:
- (UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
Cell *cell = ... dequeue ...
Object *object = ... get from your backend ...
/* configure your cell */
if ([cell.buttons count] != object.numberOfItems) {
// no need to remove and add buttons if the item count stays the same
[cell setNumberOfButtons:object.numberOfItems withTarget:self selector:#selector(buttonPressed:)];
}
for (NSInteger i = 0; i < [object.numberOfItems count]; i++) {
UIButton *button = cell.buttons[i];
[button setImage:... forState:UIControlStateNormal];
}
}
And the action would look like this:
- (IBAction)buttonPressed:(UIButton *)sender {
UICollectionView *collectionView;
CGPoint buttonOriginInCollectionView = [sender convertPoint:CGPointZero toView:collectionView];
NSIndexPath *indexPath = [collectionView indexPathForItemAtPoint:buttonOriginInCollectionView];
NSAssert(indexPath, #"can't calculate indexPath");
Cell *cell = [collectionView cellForItemAtIndexPath:indexPath];
if (cell) {
NSInteger pressedButtonIndex = [cell.buttons indexOfObject:sender];
if (pressedButtonIndex != NSNotFound) {
// do something
}
}
else {
// cell is offscreen?! why?
}
}
pretty straight forward. Get the indexPath, get the collectionViewCell, check which index the pressed button has

Access section header button in tableview when user clicks on a row of that section?

I want to access a button of a section header when user clicks on row in tableview. I can get clicked row number and that particular section by using NSIndexpath (i.e. section 1 - row 0 etc.), but could not retrieve button in the section header. I've tried using isKindOfClass by iterate through tableview, but did not work.
MainTableViewCell *clickedResourceCell = (MainTableViewCell*)btn.superview.superview;
clickedResourceCell.customThresholdBar.value = slider.value/100;
NSIndexPath *indexpath = [self.tableView indexPathForCell:clickedResourceCell];
[btn setTitle:[NSString stringWithFormat:#"%i%#", [[NSNumber numberWithFloat:[(UISlider *)sender value]] intValue], #"%"] forState:UIControlStateNormal];
self.sliderValueLabel.text = [NSString stringWithFormat:#"%i%#", [[NSNumber numberWithFloat:[(UISlider *)sender value]] intValue], #"%"];
I've got row's button updated.Now want to update section.I've tried like this!
for(UIView *view in [self.tableView subviews])
{
if([view isKindOfClass:[UIButton class]])
{
UIButton *bttn = (UIButton *)view;
if (bttn.titleLabel.tag == 7) {
if (bttn.tag == indexpath.section) {
NSLog(#"FOUND");
[bttn setTitle:[NSString stringWithFormat:#"%i%#", completedAmount/i, #"%"] forState:UIControlStateNormal];
}
}
}
}
Do it this way:
UIView *sectionHeader = [tableView headerViewForSection:indexPath.section];
UIButton *button = (UIButton*)[sectionHeader viewWithTag:<button's tag>];
whenever you have the indexpath of the row.
Good Luck!

Resources