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
Related
I am trying to create a custom questionnaire. I have multiple NSMutableArray(btnAr) where I store the groups of buttons. To keep things in order, I use another NSMutableArray(radioGroupBtns) where I store all the NSMutableArrays(btnAr).
I use tableview to display the buttons. The problem I am facing is this:
When I click on a button in the first group, after scrolling to the last group the same button is clicked also.
The right image is when I scrolled at the bottom.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 5;
}
-(UITableViewCell* )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FeedbackViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
NSInteger rowNum = [indexPath row];
NSLog(#"RowNumb: %ld",rowNum);
NSMutableArray *btns = [radioGroupBtns objectAtIndex:rowNum];
NSMutableArray *lbls = [radioGroupLabels objectAtIndex:rowNum];
for (int i=0; i<[btns count]; i++)
{
[cell addSubview:[btns objectAtIndex:i]];
[cell addSubview:[lbls objectAtIndex:i]];
}
return cell;
}
-(void) getData
{
int totalSections = 5;
for (int j=0; j<totalSections; j++)
{
NSMutableArray *btnAr = [[NSMutableArray alloc]init];
NSMutableArray *lblAr = [[NSMutableArray alloc]init];
int numOfQuestions = 4;
for (int i=0; i<numOfQuestions; i++)
{
RadioUIButton *button = [self getButton:i];
button.sectionTag = j;
button.stringTag = [NSString stringWithFormat:#"%d%d", i,button.sectionTag];
[button setTag:i];
UILabel *lbl = [self getLabel:i text:#"Question"];
[lblAr addObject:lbl];
[btnAr addObject:button];
}
[radioGroupBtns addObject:btnAr];
[radioGroupLabels addObject:lblAr];
}
}
- (void) btnPressed:(id) b
{
RadioUIButton *btn = (RadioUIButton *) b;
NSMutableArray *group = [radioGroupBtns objectAtIndex:btn.sectionTag];
for (RadioUIButton *bn in group)
{
if ([bn tag] != [b tag])
{
if ([bn isSelected])
[bn setSelected:!bn.selected];
}
}
if (![btn isSelected])
[btn setSelected:!btn.selected];
NSLog(#"Button %ld clicked. Row: %d , String: %#", (long int)[b tag], btn.sectionTag, btn.stringTag);
}
- (RadioUIButton*) getButton:(int) i {
RadioUIButton *button = [RadioUIButton buttonWithType:UIButtonTypeCustom];
int hpos = i*30 + 30;
button.frame = CGRectMake(30.0f, hpos, 30.0f, 30.0f);
[button addTarget:self action:#selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
//[button setTitle:#"Option A" forState:UIControlStateNormal];
[button setImage: [UIImage imageNamed:#"radio_button_off.png"]forState:UIControlStateNormal];
[button setImage: [UIImage imageNamed:#"radio_button_on.png"]forState: UIControlStateSelected];
return button;
}
- (UILabel*) getLabel:(int) i text:(NSString *) txt{
int hpos = i*30 + 30;
UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(80,hpos,200,30);
label.text = txt;
return label;
}
Table view reuses cells. There are ways to handle this. But, in your case you dont seem to need to reuse cells. So use scroll view instead and inflate views inside that.
And as a suggestion, try to store model objects instead of buttons. Manipulate views and their state based on the data model.
Before asking this question I googled a lot but not able to find suitable answer.
I'm have a UITableView with n number of Columns. The thing is the Column is Grouped according to a key. So my UITableView header is splitted into two, one for the column group and and this column group is divided to show columns.
I have created a custom class for the cell there I display radio button in each column.
Code:
In cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
GridTableViewCell *cell = nil; // My custom class for cell
CGFloat startX = 230;
if (cell == nil)
{
cell = [[GridTableViewCell alloc] initWithStyle1:UITableViewCellStyleDefault reuseIdentifier:#"Cell" withRows:[self.rowHeaderArray objectAtIndex:indexPath.row]];
for (int i = 0; i < [self.groupColumNmeArray count]; i++) { // groupColumNmeArray contains the Column Group name
NSArray *values = [_subColumnDict objectForKey:[self.groupColumNmeArray objectAtIndex:i]]; // subColumnDict contains the value for each column
self.originalDataArray = [CustomTableHeaderParser parseColumnInfo:values];// Parsing the values array for getting column name, type, width etc
for (CustomTableColumn *column in self.originalDataArray)
{
switch (column.columnType) // acc. to column type display the cell with values.
{
case RadioBtn:
{
_btTemp = [[UIButton alloc]initWithFrame:CGRectMake(startX, 2, subCellWidth , 40)];
[_btTemp setTag:indexPath.row];//indexPath.row];
[_btTemp addTarget:self action:#selector(radioButtonsClicked:) forControlEvents:UIControlEventTouchUpInside];
[_btTemp setImage:[UIImage imageNamed:#"radio-off.png"] forState:UIControlStateNormal];
[_btTemp setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
_btTemp.titleLabel.font =[UIFont systemFontOfSize:14.f];
[self.radioButtons addObject:_btTemp];
[cell addSubview:_btTemp];
}
break;
startX += 2+subCellWidth;
}
}
}
cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
cell.selectedBackgroundView.opaque = YES;
return cell;
}
Radio button click action method;
-(IBAction) radioButtonsClicked:(UIButton *) sender {
if ([sender isSelected]) {
[sender setSelected: NO];
[sender setImage:[UIImage imageNamed:#"radio-off.png"] forState:UIControlStateNormal];
} else {
[sender setSelected: YES];
[sender setImage:[UIImage imageNamed:#"radio-on.png"] forState:UIControlStateNormal];
}
NSLog(#"BUTTON TAG %ld",(long)sender.tag);
}
So I'm able to make selections for radio buttons in all column but actually what I want is For each column group only one radio button is selectable.
Can anybody help me. Any help would be greatly appreciable.
You can set other button's selection status as following
-(IBAction) radioButtonsClicked:(UIButton *) sender {
sender.selected = !sender.selected;
for (UIView *vw in sender.superview.subviews)
{
if([vw isKindOfClass:[UIButton class]] && vw != sender)
{
UIButton *otherBtn = (UIButton*)vw;
otherBtn.selected = NO;
}
}
}
for setting button Image - on/off, write that code at the time of creating button in cellforrow..
[_btTemp setImage:[UIImage imageNamed:#"radio-off.png"] forState:UIControlStateNormal];
[_btTemp setImage:[UIImage imageNamed:#"radio-on.png"] forState:UIControlStateSelected];
I have a UIViewController with a UICollectionView image gallery created inside it programmatically. I want to add a button to the on each uiimage of UICollectionView cell: The code in CMFViewController.h.m file for adding button to imageview is:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CMFGalleryCell *cell = (CMFGalleryCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
NSString *imageName = [self.dataArray objectAtIndex:indexPath.row];
[cell setImageName:imageName];
// [[cell myButton] addTarget:self action:#selector(myClickEvent:event) forControlEvents:UIControlEventTouchUpInside];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(80.0, 210.0, 100.0, 20.0);
[button addTarget:self action:#selector(show) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"ShowView" forState:UIControlStateNormal];
// NSMutableArray *buttonArray = [NSMutableArray arrayWithCapacity:100];
// for (int i = 0; i < 4; i++) {
// NSUInteger index = arc4random() % 4;
// newButton.frame = CGRectMake( 5, 5, 10, 10); // Whatever position and size you need...
// UIImage *buttonImage = [UIImage imageNamed:[self.dataArray objectAtIndex:indexPath.row]];
//[newButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
// [buttonArray addObject:newButton];
// }
// newButton = buttonArray; // Where myButtons is a NSArray property of your class, to store references to the buttons.
// [newButton addTarget:self action:#selector(loadImages:) forControlEvents:UIControlEventTouchUpInside];
//[newButton addTarget:self action:#selector(updateCell) forControlEvents:UIControlEventTouchUpInside];
[cell updateCell];
return cell;
}
I have tied to get help from codes at following links
adding-a-uibutton-to-a-uicollectionview
UIButton in cell in collection view not receiving touch up inside event
Please give my your suggestion and help me on this issue.
from this link u can download source code in Creating a Paged Photo Gallery With a UICollectionView: their i want to place next and previous buttons on middle lines of each image of the screen
For implementing next and previous buttons, don't added it on each image, better u add it on collection view, what chinttu-maddy-ramani told in his answer is correct, but he is doing in xib file, but programatically u can do it like below,
just add this code
Edit for requirement updating the buttons
in CMFViewController.h file make two button properties
replace by below code
#import <UIKit/UIKit.h>
#interface CMFViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
#property (nonatomic, strong) UIButton *nextButton;
#property (nonatomic, strong) UIButton *prevButton;
#end
in CMFViewController.m file
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self loadImages];
[self setupCollectionView];
[self addNextAndPreviousButtons];//add a method to add previous and next buttons
}
//hear u are adding previous and next images, but i didn't added the constraints u add it if u want t work in both orientation
- (void)addNextAndPreviousButtons
{
_nextButton = [UIButton buttonWithType:UIButtonTypeSystem];
_nextButton.frame =CGRectMake(self.view.bounds.size.width - 40, self.view.bounds.size.height/2, 50, 30);
[_nextButton setTitle:#"Next" forState:UIControlStateNormal];
[_nextButton addTarget:self action:#selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
_prevButton = [UIButton buttonWithType:UIButtonTypeSystem];
_prevButton.frame = CGRectMake(self.view.bounds.origin.x, self.view.bounds.size.height/2, 50, 30);
[_prevButton setTitle:#"Prev" forState:UIControlStateNormal];
[_prevButton addTarget:self action:#selector(previousButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_nextButton];
[self.view addSubview:_prevButton];
}
//previous button action
- (void)previousButtonAction:(id)sender
{
NSArray *visibleCell = [_collectionView visibleCells];
if(visibleCell)
{
NSIndexPath *path = [_collectionView indexPathForCell:[visibleCell lastObject]];
if(!path.row == 0)
{
NSIndexPath *nextPath = [NSIndexPath indexPathForItem:(path.row - 1) inSection:0];
[_collectionView scrollToItemAtIndexPath:nextPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
}
}
//next button action
- (void)nextButtonAction:(id)sender
{
NSArray *visibleCell = [_collectionView visibleCells];
if(visibleCell)
{
NSIndexPath *path = [_collectionView indexPathForCell:[visibleCell lastObject]];
if(path.row < [_dataArray count] - 1)
{
NSIndexPath *nextPath = [NSIndexPath indexPathForItem:(path.row + 1) inSection:0];
[_collectionView scrollToItemAtIndexPath:nextPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
}
}
//edited the method addNextAndPreviousButtons please replace it by this edited answer
//for all cases even when u are swiping
//this is to handle buttons either by tapping or navigation through swiping the collection view
- (void)updateButtons:(NSInteger)row
{
//at the beginning
if(row == 0)
{
_prevButton.hidden = YES;
_nextButton.hidden = NO;
return;
}
else if(row == ([_dataArray count] -1))
{
_nextButton.hidden = YES;
_prevButton.hidden = NO;
}
else
{
_nextButton.hidden = NO;
_prevButton.hidden = NO;
}
}
//finally u have to call updateButtons method this method
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CMFGalleryCell *cell = (CMFGalleryCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
NSString *imageName = [self.dataArray objectAtIndex:indexPath.row];
[cell setImageName:imageName];
[cell updateCell];
[self updateButtons:indexPath.row]; //update the buttons
return cell;
}
you can add button in you cell to direct drag & drop button in CMFGalleryCell.xib please check attach screenshot. and add button constraint to center horizontally and center vertically with your cell.
for suggestion only if you want next-previous functionality then you can also add button in main xib in CMFViewController.xib as per below screenshot.
I have this collapsable UITableView where there is a UITextField and a UIButton in the last cell in each table section. I would like to send the text in the UITextField to the function that is called by the UIButton that is next to it in the same cell, but I am baffled in how to achieve this. Thanks in advance for the help!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if ([self tableView:_tableView canCollapseSection:indexPath.section])
{
int num = 1;
if (self.chat[indexPath.section - 1][#"num"] != nil)
num = [self.chat[indexPath.section - 1][#"num"] intValue] + 1;
if (!indexPath.row)
{
cell.textLabel.text = self.chat[indexPath.section - 1][#"msg"]; // only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
}
else
{
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
}
}
else if (indexPath.row < num && indexPath.row >= 1)
{
cell.textLabel.text = self.chat[indexPath.section - 1][key];
cell.accessoryView = nil;
}
else
{
///////////////////////////////////////////
////////This is the important part/////////
///////////////////////////////////////////
UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(14, 6, 245, 31)];
self.sendButton = [[UIButton alloc] initWithFrame:CGRectMake(265, 1, 50, 40)];
[self.sendButton setTitle:#"Reply" forState:UIControlStateNormal];
[self.sendButton setTitleColor:UIColorFromRGB(0x960f00) forState:UIControlStateNormal];
[cell addSubview:self.sendButton];
[self.sendButton addTarget:self action:#selector(sendReply:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:field];
cell.accessoryView = nil;
}
}
else
{
cell.accessoryView = nil;
cell.textLabel.text = #"Normal Cell";
}
return cell;
}
Give some unique tag to textfield and button by below way:
///////////////////////////////////////////
////////This is the important part/////////
///////////////////////////////////////////
UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(14, 6, 245, 31)];
self.sendButton = [[UIButton alloc] initWithFrame:CGRectMake(265, 1, 50, 40)];
[self.sendButton setTitle:#"Reply" forState:UIControlStateNormal];
[self.sendButton setTitleColor:UIColorFromRGB(0x960f00) forState:UIControlStateNormal];
self.sendButton.tag = indexPath.section *1000 + indexPath.row;
[cell addSubview:self.sendButton];
[self.sendButton addTarget:self action:#selector(sendReply:) forControlEvents:UIControlEventTouchUpInside];
field.tag = self.sendButton.tag + 1;
[cell addSubview:field];
cell.accessoryView = nil;
Now on button event,
-(void) sendReply:(UIButton *)sender
{
UITextField *field = [YOOUR_TABLE_VIEW viewWithTag:sender.tag + 1];
//Do you coding here
}
Make a Custom UITableViewCell that has uitextfield and a button on it and make a protocol/delegate of that custom uitableviewcell you've created.. so you can have more control of your code and the event of your button in the future..
check this tutorial: http://www.codigator.com/tutorials/ios-uitableview-tutorial-custom-cell-and-delegates/
cheers
For this,
In cellForRowAtIndexPath: method where you are allocating the send button add one line just to give some identifier to send button as below,
[self.sendButton setAccessibilityIdentifier:[NSString stringWithFormat:#"%d#%d",indexPath.row,indexPath.section]];
Now, in sendReply: method,
//First get the row and section information
NSString *str=[sender accessibilityIdentifier];
NSArray *arr=[str componentsSeparatedByString:#"#"];
//Get the index path
NSIndexPath *iRowId =[NSIndexPath indexPathForRow:[[arr objectAtIndex:0] intValue] inSection:[arr objectAtIndex:1] intValue]];
//get the cell
UITableViewCell *objCell=(UITableViewCell*)[tblviwBasketCell cellForRowAtIndexPath:iRowId];
Now objCell will be the cell in which you have added the button and text view. so get the subviews of objCell and access the textfield to get the text.
As you say, there is a text field in each section. You should set the tag of your UIButton and UITextField same as indexPath.section.
Then, in the target method, use this tag value to get the relevant cell from the relevant section, and iterate over it's subviews to get your textField.
In the target method, you should do something like this:
- (void) sendReply:(id)sender {
int section = [(UIButton*)sender tag];
int row = [myTableView numberOfRowsInSection:section] - 1;//assuming it is the last cell in the section that contains your textField.
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell* cell = [myTableView cellForRowAtIndexPath:indexPath];
for (UIView* vu in cell.subviews) {
if ([vu isKindOfClass:[UITextField class]]) {
NSString* textString = [(UITextField*)vu text];
//perform any tasks you want with the text now
}
}
}
You can simply use viewWithTag:, since it does an iterative search, but all the extra code is to avoid iterating over all the cells before reaching your relevant cell.
I am having an issue correctly setting the image for UIButtons in a UITableViewCell. I am using a custom Cell in Storyboard with Four buttons to create a Gallery effect and loading the images from a server using an ImageLoader Delegate like in Apple's LazyTableImages' sample code. I am getting the images back from the ImageLoader just fine, the problem is setting the image.
If I set the images in the UITableView cellForRowAtIndexPath, I can set the images fine if they are already loaded or just default images:
for (int i = 0; i < [posts count] && i < [galleryButtons count]; i++)
{
post = [posts objectAtIndex:i];
UIButton *button = [galleryButtons objectAtIndex:i];
[button setTag:post.userID];
if (!post.userIcon)
{
if (tableView.dragging == NO && tableView.decelerating == NO)
{
loadFlag = YES;
}
[button setImage:[UIImage imageNamed:#"BtDefault.png"] forState:UIControlStateNormal];
} else
{
[button setImage:post.userIcon forState:UIControlStateNormal];
}
}
if (loadFlag)
{
[self startIconDownload:posts forIndexPath: indexPath];
}
However when the delegate calls the ImageDidLoad method later on, the images are not changing.
- (void)postImageDidLoad:(NSIndexPath *)indexPath forColumn:(int)postColumn
{
ImageLoader *imageLoader = [imageDownloadsInProgress objectForKey:indexPath];
Post *post;
if (imageLoader != nil)
{
UITableViewCell *cell = [timeLineTable cellForRowAtIndexPath:indexPath];
if (timeLineStyle == 1) //Gallary Style
{
int index = (indexPath.row * 4) + postColumn;
int buttonTag = 200 + postColumn + 1;
NSLog(#"Button tag is %i", buttonTag);
post = [currentPosts objectAtIndex:index];
UIButton *galleryButton = (UIButton *)[cell viewWithTag:buttonTag];
[galleryButton setImage:post.userIcon forState:UIControlStateNormal];
UIImageView *imageTester = (UIImageView *)[cell viewWithTag:300];
[imageTester setImage:post.userIcon];
[timeLineTable reloadData];
[cell setHighlighted:YES];
} else // Post Style
{
UIImageView *userImageView = (UIImageView*)[cell viewWithTag:101];
UILabel *userNameLabel = (UILabel *)[cell viewWithTag:102];
[userNameLabel setText:#"Image Loaded"];
post = [currentPosts objectAtIndex:[indexPath row]];
[userImageView setImage:post.userIcon];
}
}
}
You can see I have a UIImage in the cell for testing. This is working just fine. This code also works fine if I remove the for loop in the cellForRowAtIndexPath up above. The problem is without that for loop, the button images are not set if the images are already loaded.
I'm not sure if this is a problem with too many pointers preventing the UIButton from changing. That is all I can think of, but I am pretty new with StoryBoard and this style of Custom Cell manipulation. Thanks for any help.
Up top you set the button tag as [button setTag:post.userID]; but down the bottom you retrieve the button using the tag: int buttonTag = 200 + postColumn + 1;