UITableViewCell duplicating UITextfield subviews when scrolling - ios

I'm trying to figure out why my Subviews are duplicating when the UITableview scrolls. If I add the Subviews inside the IF statement for reusing the cell it duplicates and reorders the Subviews. If I put the code on the outside it messes up by putting the Subviews on top of one another when scrolling. Below is my code. What am I doing wrong to cause this?
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.accessoryType = UITableViewCellAccessoryNone;
UIColor *cellBackgroundColor = [rgbConverter convertColor:#"#202e35"];
cell.backgroundColor = cellBackgroundColor;
// cell.contentView.backgroundColor = color;
if ((indexPath.row == 0) && (indexPath.section == 0)) {
fullName = [[UITextField alloc] initWithFrame:CGRectMake(cell.frame.origin.x+10, cell.frame.origin.y+10, 200, 25)];
fullName.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
fullName.autocorrectionType = UITextAutocorrectionTypeNo;
[fullName setClearButtonMode:UITextFieldViewModeWhileEditing];
fullName.textColor = [UIColor lightGrayColor];
[fullName setValue:[UIColor lightGrayColor] forKeyPath:#"_placeholderLabel.textColor"];
fullName.returnKeyType = UIReturnKeyNext;
fullName.background = [UIImage imageNamed:#"textfieldBG.png"];
[fullName setTag:1];
[fullName setText:#""];
[cell.contentView addSubview:fullName];
}
if ((indexPath.row == 1) && (indexPath.section == 0)){
accountNumber = [[UITextField alloc] initWithFrame:CGRectMake(cell.frame.origin.x+10, cell.frame.origin.y+10, 200, 25)];
accountNumber.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
//accountNumber.placeholder = #"MLGW Account Number";
accountNumber.autocorrectionType = UITextAutocorrectionTypeNo;
[accountNumber setClearButtonMode:UITextFieldViewModeWhileEditing];
accountNumber.keyboardType = UIKeyboardTypeNumberPad;
accountNumber.returnKeyType = UIReturnKeyNext;
accountNumber.textColor = [UIColor lightGrayColor];
[accountNumber setValue:[UIColor lightGrayColor] forKeyPath:#"_placeholderLabel.textColor"];
[accountNumber setTag:2];
[accountNumber setText:#""];
accountNumber.background = [UIImage imageNamed:#"textfieldBG.png"];
[cell.contentView addSubview:accountNumber];
}
if ((indexPath.row == 2) && (indexPath.section == 0)){
address = [[UITextField alloc] initWithFrame:CGRectMake(cell.frame.origin.x+10, cell.frame.origin.y+10, 200, 25)];
address.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
address.placeholder = #"Address";
address.autocorrectionType = UITextAutocorrectionTypeNo;
[address setClearButtonMode:UITextFieldViewModeWhileEditing];
address.keyboardType = UIKeyboardTypeDefault;
address.returnKeyType = UIReturnKeyNext;
address.textColor = [UIColor lightGrayColor];
[address setValue:[UIColor lightGrayColor] forKeyPath:#"_placeholderLabel.textColor"];
[address setTag:3];
[address setText:#""];
address.background = [UIImage imageNamed:#"textfieldBG.png"];
[cell.contentView addSubview:address];
}
if ((indexPath.row == 3) && (indexPath.section == 0)){
aptNumber = [[UITextField alloc] initWithFrame:CGRectMake(cell.frame.origin.x+10, cell.frame.origin.y+10, 200, 25)];
aptNumber.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
aptNumber.placeholder = #"Apartment Number";
aptNumber.autocorrectionType = UITextAutocorrectionTypeNo;
aptNumber.returnKeyType = UIReturnKeyNext;
[aptNumber setClearButtonMode:UITextFieldViewModeWhileEditing];
aptNumber.keyboardType = UIKeyboardTypeNamePhonePad;
aptNumber.textColor = [UIColor lightGrayColor];
[aptNumber setValue:[UIColor lightGrayColor] forKeyPath:#"_placeholderLabel.textColor"];
[aptNumber setTag:4];
[aptNumber setText:#""];
aptNumber.background = [UIImage imageNamed:#"textfieldBG.png"];
[cell.contentView addSubview:aptNumber];
}
if ((indexPath.row == 4) && (indexPath.section == 0)){
city = [[UITextField alloc] initWithFrame:CGRectMake(cell.frame.origin.x+10, cell.frame.origin.y+10, 180, 25)];
city.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
city.placeholder = #"City";
city.autocorrectionType = UITextAutocorrectionTypeNo;
city.returnKeyType = UIReturnKeyNext;
[city setClearButtonMode:UITextFieldViewModeWhileEditing];
city.keyboardType = UIKeyboardTypeDefault;
city.textColor = [UIColor lightGrayColor];
[city setValue:[UIColor lightGrayColor] forKeyPath:#"_placeholderLabel.textColor"];
[city setTag:5];
[city setText:#""];
city.background = [UIImage imageNamed:#"textfieldBG.png"];
[cell.contentView addSubview:city];
zip = [[UITextField alloc] initWithFrame:CGRectMake(cell.frame.origin.x+210, cell.frame.origin.y+10,80, 25)];
zip.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
zip.placeholder = #"Zip";
zip.autocorrectionType = UITextAutocorrectionTypeNo;
zip.returnKeyType = UIReturnKeyNext;
[zip setClearButtonMode:UITextFieldViewModeWhileEditing];
zip.keyboardType = UIKeyboardTypeNumberPad;
zip.textColor = [UIColor lightGrayColor];
[zip setValue:[UIColor lightGrayColor] forKeyPath:#"_placeholderLabel.textColor"];
[zip setTag:6];
[zip setText:#""];
zip.background = [UIImage imageNamed:#"textfieldBG.png"];
[cell.contentView addSubview:zip];
}
if ((indexPath.row == 5) && (indexPath.section == 0)){
phoneNbr = [[UITextField alloc] initWithFrame:CGRectMake(cell.frame.origin.x+10, cell.frame.origin.y+10, 200, 25)];
phoneNbr.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
phoneNbr.placeholder = #"Phone Number";
phoneNbr.autocorrectionType = UITextAutocorrectionTypeNo;
phoneNbr.returnKeyType = UIReturnKeyNext;
[phoneNbr setClearButtonMode:UITextFieldViewModeWhileEditing];
phoneNbr.keyboardType = UIKeyboardTypeNumberPad;
phoneNbr.textColor = [UIColor lightGrayColor];
[phoneNbr setValue:[UIColor lightGrayColor] forKeyPath:#"_placeholderLabel.textColor"];
[phoneNbr setTag:7];
[phoneNbr setText:#""];
phoneNbr.background = [UIImage imageNamed:#"textfieldBG.png"];
[cell.contentView addSubview:phoneNbr];
}
if ((indexPath.row == 6) && (indexPath.section == 0)){
emailAddress = [[UITextField alloc] initWithFrame:CGRectMake(cell.frame.origin.x+10, cell.frame.origin.y+10, 200, 25)];
emailAddress.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
emailAddress.placeholder = #"Email Address";
emailAddress.returnKeyType = UIReturnKeyNext;
emailAddress.autocorrectionType = UITextAutocorrectionTypeNo;
[emailAddress setClearButtonMode:UITextFieldViewModeWhileEditing];
emailAddress.keyboardType = UIKeyboardTypeEmailAddress;
emailAddress.textColor = [UIColor lightGrayColor];
[emailAddress setValue:[UIColor lightGrayColor] forKeyPath:#"_placeholderLabel.textColor"];
[emailAddress setTag:8];
[emailAddress setText:#""];
emailAddress.background = [UIImage imageNamed:#"textfieldBG.png"];
[cell.contentView addSubview:emailAddress];
}
if ((indexPath.row == 7) && (indexPath.section == 0)){
validateEmail = [[UITextField alloc] initWithFrame:CGRectMake(cell.frame.origin.x+10, cell.frame.origin.y+10, 200, 25)];
validateEmail.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
validateEmail.placeholder = #"Re-enter Email Address";
validateEmail.returnKeyType = UIReturnKeyNext;
validateEmail.autocorrectionType = UITextAutocorrectionTypeNo;
[validateEmail setClearButtonMode:UITextFieldViewModeWhileEditing];
validateEmail.keyboardType = UIKeyboardTypeEmailAddress;
validateEmail.textColor = [UIColor lightGrayColor];
[validateEmail setValue:[UIColor lightGrayColor] forKeyPath:#"_placeholderLabel.textColor"];
[validateEmail setTag:9];
[validateEmail setText:#""];
validateEmail.background = [UIImage imageNamed:#"textfieldBG.png"];
[cell.contentView addSubview:validateEmail];
}
if ((indexPath.row == 0) && (indexPath.section == 1)){
oneTimeDonationBtn = [[UIButton alloc]initWithFrame:CGRectMake(cell.frame.origin.x+10, cell.frame.origin.y+10, 38, 32)];
[oneTimeDonationBtn setImage:[UIImage imageNamed:#"radioBox.png"] forState:UIControlStateNormal];
[oneTimeDonationBtn addTarget:self action:#selector(oneTimeAmountAction:) forControlEvents:UIControlEventTouchUpInside];
oneTimeDonation = [[UITextField alloc] initWithFrame:CGRectMake(oneTimeDonationBtn.frame.origin.x+35, cell.frame.origin.y+13, 150, 25)];
oneTimeDonation.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
oneTimeDonation.placeholder = #"One Time Donation";
oneTimeDonation.autocorrectionType = UITextAutocorrectionTypeNo;
oneTimeDonation.returnKeyType = UIReturnKeyNext;
[oneTimeDonation setClearButtonMode:UITextFieldViewModeWhileEditing];
oneTimeDonation.keyboardType = UIKeyboardTypeDecimalPad;
oneTimeDonation.textColor = [UIColor lightGrayColor];
[oneTimeDonation setValue:[UIColor lightGrayColor] forKeyPath:#"_placeholderLabel.textColor"];
[oneTimeDonation setTag:10];
[oneTimeDonation setText:#""];
oneTimeDonation.background = [UIImage imageNamed:#"textfieldBG.png"];
[cell.contentView addSubview:oneTimeDonationBtn];
[cell.contentView addSubview:oneTimeDonation];
}
if ((indexPath.row == 0) && (indexPath.section == 2)){
oneDollarBtn = [[UIButton alloc]initWithFrame:CGRectMake(cell.frame.origin.x+10, cell.frame.origin.y+10, 38, 32)];
[oneDollarBtn setImage:[UIImage imageNamed:#"radioBox.png"] forState:UIControlStateNormal];
[oneDollarBtn addTarget:self action:#selector(oneDollarAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:oneDollarBtn];
oneDollarLbl = [[UILabel alloc ] initWithFrame:CGRectMake(oneDollarBtn.frame.origin.x+35, cell.frame.origin.y+10, 38, 32)];
oneDollarLbl.text = #"$1";
oneDollarLbl.textColor = [UIColor lightGrayColor];
[cell.contentView addSubview:oneDollarLbl];
fiveDollarBtn = [[UIButton alloc]initWithFrame:CGRectMake(oneDollarLbl.frame.origin.x+35, cell.frame.origin.y+10, 38, 32)];
[fiveDollarBtn setImage:[UIImage imageNamed:#"radioBox.png"] forState:UIControlStateNormal];
[fiveDollarBtn addTarget:self action:#selector(fiveDollarAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:fiveDollarBtn];
fiveDollarLbl = [[UILabel alloc ] initWithFrame:CGRectMake(fiveDollarBtn.frame.origin.x+35, cell.frame.origin.y+10, 38, 32)];
fiveDollarLbl.text = #"$5";
fiveDollarLbl.textColor = [UIColor lightGrayColor];
[cell.contentView addSubview:fiveDollarLbl];
tenDollarBtn = [[UIButton alloc]initWithFrame:CGRectMake(fiveDollarLbl.frame.origin.x+35, cell.frame.origin.y+10, 38, 32)];
[tenDollarBtn setImage:[UIImage imageNamed:#"radioBox.png"] forState:UIControlStateNormal];
[tenDollarBtn addTarget:self action:#selector(tenDollarAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:tenDollarBtn];
tenDollarLbl = [[UILabel alloc ] initWithFrame:CGRectMake(tenDollarBtn.frame.origin.x+35, cell.frame.origin.y+10, 38, 32)];
tenDollarLbl.text = #"$10";
tenDollarLbl.textColor = [UIColor lightGrayColor];
[cell.contentView addSubview:tenDollarLbl];
}
if ((indexPath.row == 1) && (indexPath.section == 2)){
otherAmountBtn = [[UIButton alloc]initWithFrame:CGRectMake(cell.frame.origin.x+10, cell.frame.origin.y+10, 38, 32)];
[otherAmountBtn setImage:[UIImage imageNamed:#"radioBox.png"] forState:UIControlStateNormal];
[otherAmountBtn addTarget:self action:#selector(otherAmountAmountAction:) forControlEvents:UIControlEventTouchUpInside];
otherAmount = [[UITextField alloc] initWithFrame:CGRectMake(otherAmountBtn.frame.origin.x+35, cell.frame.origin.y+13, 150, 25)];
otherAmount.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
otherAmount.placeholder = #"Other Amount";
otherAmount.autocorrectionType = UITextAutocorrectionTypeNo;
otherAmount.returnKeyType = UIReturnKeyNext;
[otherAmount setClearButtonMode:UITextFieldViewModeWhileEditing];
otherAmount.keyboardType = UIKeyboardTypeDecimalPad;
otherAmount.textColor = [UIColor lightGrayColor];
[otherAmount setValue:[UIColor lightGrayColor] forKeyPath:#"_placeholderLabel.textColor"];
[otherAmount setTag:10];
[otherAmount setText:#""];
otherAmount.background = [UIImage imageNamed:#"textfieldBG.png"];
[cell.contentView addSubview:otherAmountBtn];
[cell.contentView addSubview:otherAmount];
}
if ((indexPath.row == 0) && (indexPath.section == 3)){
comments = [[UITextView alloc] initWithFrame:CGRectMake(cell.frame.origin.x+10, cell.frame.origin.y+10, 280, 100)];
comments.font = [UIFont fontWithName:#"HelveticaNeue" size:15];
comments.autocorrectionType = UITextAutocorrectionTypeNo;
comments.keyboardType = UIKeyboardTypeDefault;
comments.textColor = [UIColor lightGrayColor];
[comments setTag:11];
[comments setText:#""];
comments.contentInset = UIEdgeInsetsMake(2.0, 1.0, 0.0, 0.0);
[cell.contentView addSubview:comments];
}
}
//cell.imageView.image = [UIImage imageNamed:#"settings_icon.png"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.backgroundColor = [UIColor clearColor];
return cell;
}

This happens when you are using only ONE cellIdentifier to reuse different kind of cells by invoke: dequeueReusableCellWithIdentifier method.
In your code, you are adding different view at different indexPath, but you don't know what cell is given by dequeueReusableCellWithIdentifier method.
For example, when you add address view to a reused cell, it could already have a fullName subview on it. Then you will get an unexpected result.
There are many ways to solve the problem.
Here are two that I think is easy for your situation, you can chose any one you like:
Since your cell contents are not so "reusable", if the performance is not a problem, I recommend you not to use dequeueReusableCellWithIdentifier at all.
You'd better use different cellIdentifier for different kind of cell.

The main reason is that dequeueReusableCellWithIdentifier, as the name suggests, gets a cell already created regardless of order. I guess it caches only as many cells as visible ones.
When you scroll up, it gives you a created (and filled) cell.
Replace the cell creation by this:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
Also remove the if (cell == nil). Also remove the other cell creation
Remember that dequeueReusableCellWithIdentifier:forIndexPath: never returns nil. So it is a good idea to check if the cell was already filled to skip the subviews creation.

Your code is a little hard to go through.
Every time you have to customize the cell a lot , then you should not use UITableViewCell, instead you should subclass it, and customize it in your custom class.
In my experience I find if statement complex when both section and rows are involved.
I suggest you to use switch statement, where you can provide logic for each case.
This will make your life easier, something along the lines:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (indexPath.section) {
case 0:
switch (indexPath.row) {
case 0:
//fullName custom cell
break;
case 1:
//account number custom cell
break;
default:
break;
}
break;
default:
break;
}
return cell;
}

First set textfield tag to some constant, you can fetch text fields by using cell indexPath.Secondly add textfield if its not already there like below;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//check if you already have textfield, say a constant tag is 100
UITextField *myTextField ;
if(cell){
myTextField = (UITextField *)[cell.contentView viewWithTag:100];
}
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
//now if myTextField is nil then only init it
if(!myTextField){
//Configure textfield here and add to cell content view
}
}
//now all things are configure for cell , assign whatever text you want to myTextField
if(indexPath.row == 0 && indexPath.section == 0){
//.......
[myTextField setText:#"XYZ"];
}
}

Related

IOS, How to set Auto Layout in your UITableViewCell that contains different Subviews

I have a layout issue, i have a UIView that contains an UIImageView and three other UILabels. The part that needs to set the layout dynamically is the main UIView thats added to the cell and a UILabel that will contain text of any length lets say for this example.
What i have done i created a custom UITableViewCell and added the SubViews to the custom UITableViewCell, like here:
-(void)setupView:(PostInfo*)postInfo{
CGRect screenRect = [[UIScreen mainScreen] bounds];
viewPostMessage = [[UIView alloc] initWithFrame:CGRectMake(10, 10, screenRect.size.width - 20, 100)];
viewPostMessage.backgroundColor = [UIColor colorWithRed:193.0f/255 green:193.0f/255 blue:193.0f/255 alpha:1.0f];
viewPostMessage.layer.borderColor = [UIColor blackColor].CGColor;
viewPostMessage.layer.borderWidth = 0.5f;
if(postInfo.userImage.length > 0){
userImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
UIImage *imageUser = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: [NSString stringWithFormat:#"http://www.hugt.co.uk/userimage/%d/userImage.jpg", postInfo.userId]]]];
userImage.image = imageUser;
[viewPostMessage addSubview:userImage];
}else{
UIView *viewImage = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
viewImage.backgroundColor = [UIColor colorWithRed:132.0f/255 green:132.0f/255 blue:132.0f/255 alpha:1.0f];
[viewPostMessage addSubview:viewImage];
userImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
UIImage *imageUser = [UIImage imageNamed:#"defaultuser.jpg"];
userImage.image = imageUser;
[viewImage addSubview:userImage];
}
labelUserName = [[UILabel alloc] initWithFrame:CGRectMake(50, 8, 200, 16)];
labelUserName.textColor = [UIColor colorWithRed:56.0f/255 green:56.0f/255 blue:57.0f/255 alpha:1.0f];
labelUserName.text = [NSString stringWithFormat:#"%# %# posted...", postInfo.firstName,postInfo.lastName];
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelUserName.font = [UIFont fontWithName:#"Helvetica" size:12];
labelUserName.userInteractionEnabled = YES;
[viewPostMessage addSubview:labelUserName];
labelCreated = [[UILabel alloc] initWithFrame:CGRectMake(50, 24, 200, 16)];
labelCreated.textColor = [UIColor colorWithRed:86.0f/255 green:152.0f/255 blue:179.0f/255 alpha:1.0f];
labelCreated.text = [NSDateFormatter localizedStringFromDate:postInfo.timeStampCreated dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
labelCreated.text = [labelCreated.text stringByReplacingOccurrencesOfString:#"AM" withString:#""];
labelCreated.text = [labelCreated.text stringByReplacingOccurrencesOfString:#"PM" withString:#""];
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelCreated.font = [UIFont fontWithName:#"Helvetica" size:12];
labelCreated.userInteractionEnabled = YES;
[viewPostMessage addSubview:labelCreated];
labelMessage = [[UILabel alloc] initWithFrame:CGRectMake(50, 43, 210, 50)];
labelMessage.textColor = [UIColor colorWithRed:141.0f/255 green:142.0f/255 blue:142.0f/255 alpha:1.0f];
labelMessage.text = postInfo.message;
labelMessage.numberOfLines = 3;
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelMessage.font = [UIFont fontWithName:#"Helvetica" size:12];
labelMessage.userInteractionEnabled = YES;
[labelMessage sizeToFit];
[viewPostMessage addSubview:labelMessage];
[self.contentView addSubview:viewPostMessage];
}
When i create this custom UITableViewCell i pass in an object that sets the text on the UILabels, like this:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cell";
if(tableViewThreads == tableView){
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
ThreadInfo *threadInfo = (ThreadInfo*)[self.threadsArray objectAtIndex:indexPath.row];
[cell.contentView addSubview:[self setupThreadItem:threadInfo]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
if(tableViewPosts == tableView){
PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[PostTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
PostInfo *postInfo = (PostInfo*)[self.postsArray objectAtIndex:indexPath.row];
[cell setupView:postInfo];
//[cell addSubview:[self setupPostItem:postInfo]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
//[cell.contentView addSubview:[self setupThreadItem:threadInfo]];
}
return nil;
}
I have searched the web and also here to find out how to Auto Layout the Subviews in the cell but can't seem to understand what needs to go next. I read that you need a Prototype Cell so i created a custom UITableViewCell and thats how far I've got.
Any help would be appreciated, thanks.
So far i have got the cells to resize with Auto Layout but i have removed the UIView that sits inside the cell, so now i have three UILabels and an UIImageView which are the UIImageView (userImage), UILabel (labelUsername), UILabel (labelCreated) and UILabel (labelMessage). So the dimensions and coordinates are the same just that the UIView has been removed:
First i set up NSLayoutContsraints in my Custom Cell, code bellow:
Set numberOFLines = 0 and remove sizeToFit on the UILabel thats going to AutoLayout.
-(void)setupView:(PostInfo*)postInfo{
CGRect screenRect = [[UIScreen mainScreen] bounds];
viewPostMessage = [[UIView alloc] initWithFrame:CGRectMake(10, 10, screenRect.size.width - 20, 100)];
viewPostMessage.backgroundColor = [UIColor colorWithRed:193.0f/255 green:193.0f/255 blue:193.0f/255 alpha:1.0f];
viewPostMessage.layer.borderColor = [UIColor blackColor].CGColor;
viewPostMessage.layer.borderWidth = 0.5f;
if(postInfo.userImage.length > 0){
userImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
UIImage *imageUser = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: [NSString stringWithFormat:#"http://www.hugt.co.uk/userimage/%d/userImage.jpg", postInfo.userId]]]];
userImage.image = imageUser;
[self.contentView addSubview:userImage];
}else{
UIView *viewImage = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
viewImage.backgroundColor = [UIColor colorWithRed:132.0f/255 green:132.0f/255 blue:132.0f/255 alpha:1.0f];
[self.contentView addSubview:viewImage];
userImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
UIImage *imageUser = [UIImage imageNamed:#"defaultuser.jpg"];
userImage.image = imageUser;
[viewImage addSubview:userImage];
}
labelUserName = [[UILabel alloc] initWithFrame:CGRectMake(50, 8, 200, 16)];
labelUserName.textColor = [UIColor colorWithRed:56.0f/255 green:56.0f/255 blue:57.0f/255 alpha:1.0f];
labelUserName.text = [NSString stringWithFormat:#"%# %# posted...", postInfo.firstName,postInfo.lastName];
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelUserName.font = [UIFont fontWithName:#"Helvetica" size:12];
labelUserName.userInteractionEnabled = YES;
[self.contentView addSubview:labelUserName];
labelCreated = [[UILabel alloc] initWithFrame:CGRectMake(50, 24, 200, 16)];
labelCreated.textColor = [UIColor colorWithRed:86.0f/255 green:152.0f/255 blue:179.0f/255 alpha:1.0f];
labelCreated.text = [NSDateFormatter localizedStringFromDate:postInfo.timeStampCreated dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
labelCreated.text = [labelCreated.text stringByReplacingOccurrencesOfString:#"AM" withString:#""];
labelCreated.text = [labelCreated.text stringByReplacingOccurrencesOfString:#"PM" withString:#""];
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelCreated.font = [UIFont fontWithName:#"Helvetica" size:12];
labelCreated.userInteractionEnabled = YES;
[self.contentView addSubview:labelCreated];
labelMessage = [[UILabel alloc] initWithFrame:CGRectMake(50, 43, 210, 50)];
labelMessage.textColor = [UIColor colorWithRed:141.0f/255 green:142.0f/255 blue:142.0f/255 alpha:1.0f];
labelMessage.text = postInfo.message;
labelMessage.numberOfLines = 0;
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelMessage.font = [UIFont fontWithName:#"Helvetica" size:12];
labelMessage.userInteractionEnabled = YES;
labelMessage.lineBreakMode = NSLineBreakByWordWrapping;
//[labelMessage sizeToFit];
[self.contentView addSubview:labelMessage];
labelMessage.translatesAutoresizingMaskIntoConstraints = NO;
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-10-[bodyLabel]-19-|" options:0 metrics:nil views:#{ #"bodyLabel": labelMessage }]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-43-[bodyLabel]-6-|" options:0 metrics:nil views:#{ #"bodyLabel": labelMessage }]];
//[self.contentView addSubview:viewPostMessage];
}
Then in my ViewController that contains the UITableVIew, i modified this bit of code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"cell";
if(tableViewThreads == tableView){
return 122;
}
if(tableViewPosts == tableView){
PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[PostTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
PostInfo *postInfo = (PostInfo*)[self.postsArray objectAtIndex:indexPath.row];
[cell setupView:postInfo];
[cell setNeedsLayout];
[cell layoutIfNeeded];
CGFloat h = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return h + 1;
}
return 0;
}
The Cells do now resize and the UILabel resizes automatically now but my other problem is that the UITableView scroll is not smooth so ill have to fix that, and when i scroll in the UITableView the Cell data from the UILabel (labelMessage) seems to print it self in other cells, don't know why this is
BUT the Cells resize and the other issues ill ask another question on here.
Sorry forgot to add this bit of code that sits in the PostTableViewCell:
- (void)layoutSubviews
{
[super layoutSubviews];
// Make sure the contentView does a layout pass here so that its subviews have their frames set, which we
// need to use to set the preferredMaxLayoutWidth below.
[self.contentView setNeedsLayout];
[self.contentView layoutIfNeeded];
// Set the preferredMaxLayoutWidth of the mutli-line bodyLabel based on the evaluated width of the label's frame,
// as this will allow the text to wrap correctly, and as a result allow the label to take on the correct height.
labelMessage.preferredMaxLayoutWidth = CGRectGetWidth(labelMessage.frame);
}

UiTableViewHeader - Dynamic button event handler

I need to add a uiButton to a static uitableview section header - I've made an attempt with the following -
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
// you can get the title you statically defined in the storyboard
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
CGRect frame = tableView.bounds;
// create and return a custom view
#define LABEL_PADDING 10.0f
HeaderLabelStyling *customLabel = [[HeaderLabelStyling alloc] initWithFrame:CGRectInset(frame, LABEL_PADDING, 0)] ;
UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(frame.size.width-60, 10, 50, 30)];
addButton.backgroundColor = [UIColor whiteColor];
addButton.titleLabel.textColor = [UIColor colorWithRed:240/255.0f green:118/255.0f blue:34/255.0f alpha:1.0f];
addButton.titleLabel.tintColor = [UIColor blackColor];
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
title.text = #"iawn";
customLabel.text = sectionTitle;
customLabel.backgroundColor= [UIColor colorWithRed:143.0f/255.0f green:137.0f/255.0f blue:135.0f/255.0f alpha:1.0f];
customLabel.textColor = [UIColor colorWithRed:255/255.0f green:255/255.0f blue:255/255.0f alpha:1.0f];
[customLabel addSubview:addButton];
[addButton addSubview:title];
[addButton addTarget:self action:#selector(receiverButtonClicked:) forControlEvents:UIControlEventTouchDown];
return customLabel;
}
-(void)receiverButtonClicked:(id)sender{
NSLog(#"button clicked");
}
the above adds a button - but doesn't react to the click event - can anyone suggest how I can get this to work?
UILabel does not handles touches by default.
Add following line of code:
customLabel.userInteractionsEnabled = YES;
In order to display button only for third section you should add following condition:
if(section == 2){...}
So your -tableView:viewForHeaderInSection: should look as follows:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection (NSInteger)section {
if(section != 2) return nil;
// you can get the title you statically defined in the storyboard
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
CGRect frame = tableView.bounds;
// create and return a custom view
#define LABEL_PADDING 10.0f
HeaderLabelStyling *customLabel = [[HeaderLabelStyling alloc] initWithFrame:CGRectInset(frame, LABEL_PADDING, 0)] ;
UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(frame.size.width-60, 10, 50, 30)];
addButton.backgroundColor = [UIColor whiteColor];
addButton.titleLabel.textColor = [UIColor colorWithRed:240/255.0f green:118/255.0f blue:34/255.0f alpha:1.0f];
addButton.titleLabel.tintColor = [UIColor blackColor];
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
title.text = #"iawn";
customLabel.text = sectionTitle;
customLabel.backgroundColor= [UIColor colorWithRed:143.0f/255.0f green:137.0f/255.0f blue:135.0f/255.0f alpha:1.0f];
customLabel.userInteractionsEnabled = YES;
customLabel.textColor = [UIColor colorWithRed:255/255.0f green:255/255.0f blue:255/255.0f alpha:1.0f];
[customLabel addSubview:addButton];
[addButton addSubview:title];
[addButton addTarget:self action:#selector(receiverButtonClicked:) forControlEvents:UIControlEventTouchDown];
return customLabel;
}

UITableview Cell Height is not calculated properly and cells overlap

I need to create and populate custom cells. These cells height are huge about 300-400.
So I have a populateCellView function , I call that function on heightForRowAtIndexPath to calculate height and in cellForRowAtIndexPath to add that view to cell content view, but somehow sometimes cells overlap.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [self populateCellView:indexPath.row].frame.size.height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *populateCell= nil;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
populateCell=[[UIView alloc] initWithFrame:CGRectZero];
[[populateCell layer] setBorderWidth:2.0f];
populateCell= [self populateCellView:indexPath.row];
[[cell contentView] addSubview:populateCell];
}
if (!populateCell){
populateCell = (UIView*)[cell viewWithTag:1];
populateCell= [self populateCellView:indexPath.row];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
populate view function:
-(UIView *)populateCellView:(int)forCase
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width,500)];
[view setBackgroundColor:[UIColor colorWithRed:40/255.0 green:150/255.0 blue:213/255.0 alpha:1.0]];
view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
if ([view subviews]){
for (UIView *subview in [view subviews]) {
[subview removeFromSuperview];
}
}
UILabel *caseNumberLabel;
UILabel *caseNameLabel;
UILabel *caseSummaryLabel;
UILabel *caseAncLabel;
UILabel *caseNumberText;
UILabel *caseNameText;
UILabel *caseSummaryText;
UILabel *caseAncText;
//static label for case number
caseNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,10,250, 50)];
caseNumberLabel.textColor = [UIColor whiteColor];
caseNumberLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
caseNumberLabel.text =#"Case Number:";
caseNumberLabel.backgroundColor = [UIColor clearColor];
caseNumberLabel.numberOfLines=0;
caseNumberLabel.adjustsFontSizeToFitWidth = NO;
caseNumberLabel.tag=forCase;
caseNumberLabel.frame=[self calculateLabelFrame:caseNumberLabel];
//case number from plist
caseNumberText = [[UILabel alloc] initWithFrame:CGRectMake(caseNumberLabel.frame.size.width+50,caseNumberLabel.frame.origin.y,self.view.frame.size.width-caseNumberLabel.frame.size.width-50, 50)];
caseNumberText.textColor = [UIColor whiteColor];
caseNumberText.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:24.0f];
caseNumberText.text =[[self agenda] getCaseNumber:forCase];
caseNumberText.backgroundColor = [UIColor clearColor];
caseNumberText.numberOfLines=0;
caseNumberText.adjustsFontSizeToFitWidth = NO;
caseNumberText.tag=forCase;
//[caseNumberLabel sizeToFit];
caseNumberText.frame=[self calculateLabelFrame:caseNumberText];
//static label for case name
caseNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,caseNumberText.frame.origin.y + caseNumberText.bounds.size.height+5,250, 50)];
caseNameLabel.textColor =[UIColor whiteColor];
caseNameLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
caseNameLabel.text =#"Case Name:";
caseNameLabel.backgroundColor = [UIColor clearColor];
caseNameLabel.numberOfLines=0;
caseNameLabel.adjustsFontSizeToFitWidth = NO;
caseNameLabel.tag=forCase;
//[caseNumberLabel sizeToFit];
caseNameLabel.frame=[self calculateLabelFrame:caseNameLabel];
//case name from plist
caseNameText = [[UILabel alloc] initWithFrame:CGRectMake(caseNameLabel.frame.size.width+50,caseNameLabel.frame.origin.y,self.view.frame.size.width-caseNameLabel.frame.size.width-50, 50)];
caseNameText.textColor = [UIColor whiteColor];
caseNameText.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:24.0f];
caseNameText.text =[[self agenda] getCaseName:forCase];
caseNameText.backgroundColor = [UIColor clearColor];
caseNameText.numberOfLines=0;
//caseNameText.adjustsFontSizeToFitWidth = NO;
caseNameText.tag=forCase;
[caseNameText sizeToFit];
//caseNameText.lineBreakMode = NSLineBreakByWordWrapping;
caseNameText.frame=[self calCellLabelFrame:caseNameText previousLabel:caseNameLabel];
//static label for case summary
caseSummaryLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,caseNameText.frame.origin.y + caseNameText.bounds.size.height+20,250, 50)];
caseSummaryLabel.textColor = [UIColor whiteColor];
caseSummaryLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
caseSummaryLabel.text =#"Case Summary:";
caseSummaryLabel.backgroundColor = [UIColor clearColor];
caseSummaryLabel.numberOfLines=0;
caseSummaryLabel.adjustsFontSizeToFitWidth = NO;
caseSummaryLabel.tag=forCase;
//[caseSummaryLabel sizeToFit];
caseSummaryLabel.frame=[self calculateLabelFrame:caseSummaryLabel];
//case name from plist
caseSummaryText = [[UILabel alloc] initWithFrame:CGRectMake(caseSummaryLabel.frame.size.width+50,caseSummaryLabel.frame.origin.y,self.view.frame.size.width-caseSummaryLabel.frame.size.width-100, 50)];
caseSummaryText.textColor = [UIColor whiteColor];
caseSummaryText.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:24.0f];
caseSummaryText.text =[[self agenda] getCaseSummary:forCase];
caseSummaryText.backgroundColor = [UIColor clearColor];
caseSummaryText.numberOfLines=0;
//caseSummaryText.adjustsFontSizeToFitWidth = NO;
caseSummaryText.tag=forCase;
[caseSummaryText sizeToFit];
//caseSummaryText.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
caseSummaryText.frame=[self calCellLabelFrame:caseSummaryText previousLabel:caseSummaryLabel];
//static label for anc
caseAncLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,caseSummaryText.frame.origin.y + caseSummaryText.bounds.size.height+15,250, 50)];
caseAncLabel.textColor = [UIColor whiteColor];
caseAncLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
caseAncLabel.text =#"ANC:";
caseAncLabel.backgroundColor = [UIColor clearColor];
caseAncLabel.numberOfLines=0;
caseAncLabel.adjustsFontSizeToFitWidth = NO;
caseAncLabel.tag=forCase;
//[ccaseAncLabel sizeToFit];
caseAncLabel.frame=[self calculateLabelFrame:caseAncLabel];
//case name from plist
caseAncText = [[UILabel alloc] initWithFrame:CGRectMake(caseAncLabel.frame.size.width+50,caseAncLabel.frame.origin.y,self.view.frame.size.width-caseAncLabel.frame.size.width-50, 50)];
caseAncText.textColor = [UIColor whiteColor];
caseAncText.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:24.0f];
caseAncText.text =[[self agenda] getCaseAnc:forCase];
caseAncText.backgroundColor = [UIColor clearColor];
caseAncText.numberOfLines=0;
//caseAncText.adjustsFontSizeToFitWidth = NO;
caseAncText.tag=forCase;
[caseAncText sizeToFit];
//caseSummaryText.lineBreakMode = NSLineBreakByWordWrapping;
caseAncText.frame=[self calCellLabelFrame:caseAncText previousLabel:caseAncLabel];
//add button
UIButton *acceptButton=[UIButton buttonWithType:UIButtonTypeCustom];
[acceptButton setTag:forCase];
acceptButton.titleLabel.tag=1;
[acceptButton setFrame:CGRectMake(caseAncLabel.frame.size.width+50,caseAncText.frame.origin.y + caseAncText.bounds.size.height+20,181,39)];
NSString *radioButtonImage=#"view_attachment.png";
UIImage *acceptbuttonImage = [UIImage imageNamed:radioButtonImage];
[acceptButton setBackgroundImage:acceptbuttonImage forState:UIControlStateNormal];
[acceptButton addTarget:self action:#selector(showAttachements:) forControlEvents:UIControlEventTouchUpInside];
//whie line
UIView *anotherline = [[UIView alloc] initWithFrame:CGRectMake(0, acceptButton.frame.origin.y + acceptButton.bounds.size.height+15, self.view.frame.size.width, 1)];
anotherline.backgroundColor=[UIColor whiteColor];
anotherline.tag=forCase;
[view addSubview:acceptButton];
[view addSubview: caseNumberLabel];
[view addSubview:caseNumberText];
[view addSubview:caseNameLabel];
[view addSubview:caseNameText];
[view addSubview:caseSummaryLabel];
[view addSubview:caseSummaryText];
[view addSubview:caseAncText];
[view addSubview:caseAncLabel];
[view addSubview:anotherline];
view.frame = CGRectMake(0,0, self.view.frame.size.width,anotherline.frame.origin.y + anotherline.bounds.size.height+5);
CGFloat redLevel = rand() / (float) RAND_MAX;
CGFloat greenLevel = rand() / (float) RAND_MAX;
CGFloat blueLevel = rand() / (float) RAND_MAX;
view.backgroundColor = [UIColor colorWithRed: redLevel
green: greenLevel
blue: blueLevel
alpha: 1.0];
return view;
}
I call reload data like this
dispatch_async(dispatch_get_main_queue(), ^{
[_agenda loadFromPlist];
[[self tableView] reloadData];
});
Any idea why cells overlaps?
Its your UITableview cellforIndexPath causing overlap
try this
if (!populateCell){
populateCell = (UIView*)[cell viewWithTag:1];
populateCell= [self populateCellView:indexPath.row];
if ([[cell contentView] subviews]){
for (UIView *subview in [[cell contentView] subviews]) {
[subview removeFromSuperview];
}
}
[[cell contentView] addSubview:populateCell];
}
cell.backgroundColor=[UIColor clearColor];
At the end of the UITableViewDataSource method, tableView:cellForRowAtIndexPath:, you have to call [[cell contentView] addSubView:populateCell]. If the table dequeued a cell successfully, you have to retrieve the appropriate populateCell and add it to the contentView.
If you use storyboards, and set a different height for the cells, and the rows in the tableview, the height will usually overlap. The other answers are also highly valid, but usually when I've encountered this problem, the bug lies in a different value on row height and cell height in the tableview object in your storyboard...

UITable view not displaying button in cell iOS

i have implemented this code, its showing both labels, but button not coming in cell tell me the issue
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"ImageOnRightCell";
UILabel *mainLabel, *secondLabel;
UIButton *buttonMe;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
mainLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 220.0, 15.0)];
mainLabel.tag = MAINLABEL_TAG;
mainLabel.font = [UIFont systemFontOfSize:14.0];
mainLabel.textAlignment = UITextAlignmentRight;
mainLabel.textColor = [UIColor blackColor];
mainLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:mainLabel];
secondLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 20.0, 220.0, 25.0)];
secondLabel.tag = SECONDLABEL_TAG;
secondLabel.font = [UIFont systemFontOfSize:12.0];
secondLabel.textAlignment = UITextAlignmentRight;
secondLabel.textColor = [UIColor darkGrayColor];
secondLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:secondLabel];
buttonMe = [[UIButton alloc] initWithFrame:CGRectMake(260.0, 7.0, 30.0, 30.0)];
buttonMe.tag = PHOTO_TAG;
buttonMe.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:buttonMe];
}
else {
mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
buttonMe = (UIButton *)[cell.contentView viewWithTag:PHOTO_TAG];
}
mainLabel.text = #"main text";
secondLabel.text = #"Secon text";
buttonMe.titleLabel.text=#"oh";
return cell;
}
please help for this
I think the problem is with
buttonMe = [[UIButton alloc] initWithFrame:CGRectMake(260.0, 7.0, 30.0, 30.0)];
it will give you back a UIButton of type UIButtonTypeCustom which will by default be transparent/Clear color.
so may be it is getting added on the cell but is not visible, try and change the background color of the button and check if its still not visible.
To create button programatically use this code
UIButton *buttonMe = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[buttonMe addTarget:self
action:#selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[buttonMe setTitle:#"Show View" forState:UIControlStateNormal];
buttonMe.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
buttonMe.tag = PHOTO_TAG;
buttonMe.frame = CGRectMake(260.0, 7.0, 30.0, 30.0);
[cell.contentView addSubview:buttonMe];
Note i included the code for setting the action also.When you click it will try the method aMethod: ,so define it also ,otherwise will appear a crash on button click event
Try this, set backgroundColor for buttonMe:buttonMe.backgroundColor = [UIColor grayColor];
and change "buttonMe.titleLabel.text=#"oh"" to "[buttonMe setTitle:#"oh" forState:UIControlStateNormal];"

UItableview cells get mixed up (again)

Basically I have this UItableview that when generated is composed of 2 cells : one with scores and if you touch the other one it inserts another row of scores.
All of this works great but when I scroll and the first cell goes out of the screen, when it comes back it adds another one on top of it (it superposes it)!
I guess I am doing something wrong with dequeueReusableCellWithIdentifier and addSubview but I can't figure out what it is...
Here is my code :
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
int feedIndex = [indexPath indexAtPosition:[indexPath length] - 1];
static NSString *CellIdentifier1 = #"Cell1";
static NSString *CellIdentifier2 = #"Cell2";
if (feedIndex == 0)// configures the first cell
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1 forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier1];
textField1 = [[UITextField alloc] initWithFrame:CGRectMake(0, (44 - 15) / 2.0, 80, 15)];
textField1.font = [UIFont boldSystemFontOfSize:15];
textField1.tag = i+1;// to keep track of the cells that are created by the user
i++;
textField1.textAlignment = UITextAlignmentCenter;
[textField1 addTarget:self//to get rid of the keyboard
action:#selector(saisieReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
textField1.text = #"00";
[cell.contentView addSubview:textField1];
textField2 = [[UITextField alloc] initWithFrame:CGRectMake(80, (44 - 15) / 2.0, 80, 15)];
textField2.font = [UIFont boldSystemFontOfSize:15];
textField2.tag = i+1;
i++;
textField2.textAlignment = UITextAlignmentCenter;
[textField2 addTarget:self
action:#selector(saisieReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
textField2.text = #"00";
[cell.contentView addSubview:textField2];
textField3 = [[UITextField alloc] initWithFrame:CGRectMake(160, (44 - 15) / 2.0, 80, 15)];
textField3.font = [UIFont boldSystemFontOfSize:15];
textField3.tag = i+1;
i++;
textField3.textAlignment = UITextAlignmentCenter;
[textField3 addTarget:self
action:#selector(saisieReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
textField3.text = #"00";
[cell.contentView addSubview:textField3];
textField4 = [[UITextField alloc] initWithFrame:CGRectMake(240, (44 - 15) / 2.0, 80, 15)];
textField4.font = [UIFont boldSystemFontOfSize:15];
textField4.tag = i+1;
i++;
textField4.textAlignment = UITextAlignmentCenter;
[textField4 addTarget:self
action:#selector(saisieReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
textField4.text = #"00";
[cell.contentView addSubview:textField4];
}
return cell;
}
else if (feedIndex == nbrow -1) //configures the second cell
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2 forIndexPath:indexPath];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2];
}
cell.textLabel.text = #"Add score";
return cell;
}
else // configures all of the other cells that are created by the user when he clicks and the second cell
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1 forIndexPath:indexPath];
textField1 = [[UITextField alloc] initWithFrame:CGRectMake(0, (44 - 15) / 2.0, 80, 15)];
textField1.font = [UIFont boldSystemFontOfSize:15];
textField1.tag = i+1;
i++;
textField1.textAlignment = UITextAlignmentCenter;
[textField1 addTarget:self//to get rid of the keyboard
action:#selector(saisieReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
textField1.text = #"00";
[cell.contentView addSubview:textField1];
textField2 = [[UITextField alloc] initWithFrame:CGRectMake(80, (44 - 15) / 2.0, 80, 15)];
textField2.font = [UIFont boldSystemFontOfSize:15];
textField2.tag = i+1;
i++;
textField2.textAlignment = UITextAlignmentCenter;
[textField2 addTarget:self
action:#selector(saisieReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
textField2.text = #"00";
[cell.contentView addSubview:textField2];
textField3 = [[UITextField alloc] initWithFrame:CGRectMake(160, (44 - 15) / 2.0, 80, 15)];
textField3.font = [UIFont boldSystemFontOfSize:15];
textField3.tag = i+1;
i++;
textField3.textAlignment = UITextAlignmentCenter;
[textField3 addTarget:self
action:#selector(saisieReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
textField3.text = #"00";
[cell.contentView addSubview:textField3];
textField4 = [[UITextField alloc] initWithFrame:CGRectMake(240, (44 - 15) / 2.0, 80, 15)];
textField4.font = [UIFont boldSystemFontOfSize:15];
textField4.tag = i+1;
i++;
textField4.textAlignment = UITextAlignmentCenter;
[textField4 addTarget:self
action:#selector(saisieReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
textField4.text = #"00";
[cell.contentView addSubview:textField4];
return cell;
}}
I am new with developing for iOS and I am facing my first problem programming my first app!
I have been looking all over internet but even if I have found threads with similar problems, I can't manage to solve mine.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1 forIndexPath:indexPath];
textField1 = [[UITextField alloc] initWithFrame:CGRectMake(0, (44 - 15) / 2.0, 80, 15)];
textField1.font = [UIFont boldSystemFontOfSize:15];
textField1.tag = i+1;
i++;
textField1.textAlignment = UITextAlignmentCenter;
[textField1 addTarget:self//to get rid of the keyboard
action:#selector(saisieReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
textField1.text = #"00";
[cell.contentView addSubview:textField1];
textField2 = [[UITextField alloc] initWithFrame:CGRectMake(80, (44 - 15) / 2.0, 80, 15)];
textField2.font = [UIFont boldSystemFontOfSize:15];
textField2.tag = i+1;
i++;
textField2.textAlignment = UITextAlignmentCenter;
[textField2 addTarget:self
action:#selector(saisieReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
textField2.text = #"00";
[cell.contentView addSubview:textField2];
textField3 = [[UITextField alloc] initWithFrame:CGRectMake(160, (44 - 15) / 2.0, 80, 15)];
textField3.font = [UIFont boldSystemFontOfSize:15];
textField3.tag = i+1;
i++;
textField3.textAlignment = UITextAlignmentCenter;
[textField3 addTarget:self
action:#selector(saisieReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
textField3.text = #"00";
[cell.contentView addSubview:textField3];
textField4 = [[UITextField alloc] initWithFrame:CGRectMake(240, (44 - 15) / 2.0, 80, 15)];
textField4.font = [UIFont boldSystemFontOfSize:15];
textField4.tag = i+1;
i++;
textField4.textAlignment = UITextAlignmentCenter;
[textField4 addTarget:self
action:#selector(saisieReturn:)
forControlEvents:UIControlEventEditingDidEndOnExit];
textField4.text = #"00";
[cell.contentView addSubview:textField4];
return cell;

Resources