I'm working on a registration form actually and i'm facing some kind of trouble.
I'm using an UITextField into my cell and I wrote a string into the placeholder. Everything runs fine until I try to center the UITextField.textAlignment. It, somehow, manages not to center it. I checked it up and did some test and I think it might be an issue du to Constraints (I really want my form to work for the iphone 4s, 5, 6 and 6+ screens). It looks almost centered when i'm on iphone 6 but then you see the string less and less centered, going for right side if you switch to iphone 5 then iphone 4s.. So far I only used both heights Constraints.
Now the "good" thing is when I scroll my tableView, if my cells get out of sight, once I reload my cells, the placeholder string appears a second time but in the right place (the real center this time) with the old missplaced placeholder string. I would like this placeholder showing when I scroll appears when I first load my table because it seems it is the exact result I want to get. But this only appears when I try to center the placeholder, if i don't, there is no second placeholder string showing. I'll give you 2 links for the pictures, since my english is terrible, you guys might be able to understand better this way.
+= Nothing is happening into my code when I scroll the tableView, it is running the same CellForRowAtIndexPath but still with different result.
Thank you for all advices and help you guys will bring to me
Normal screen with Placeholder not totally on center:
Buggy screen with the second Placeholder on right position:
Here is my code running:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = #"id";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
if (indexPath.section == 0){
self.LastName = [[UITextField alloc] initWithFrame:cell.contentView.bounds];
self.LastName.placeholder= #"Last Name";
self.LastName.autocorrectionType = UITextAutocorrectionTypeNo;
self.LastName.textAlignment = NSTextAlignmentCenter;
self.LastName.delegate = self;
[self.LastName setValue:[UIColor whiteColor] forKeyPath:#"_placeholderLabel.textColor"];
[self.LastName setTextColor:[UIColor whiteColor]];
[cell.contentView addSubview:self.LastName];
[cell.contentView.layer setBorderColor:[UIColor whiteColor].CGColor];
}
else if (indexPath.section == 1)
{
self.Name = [[UITextField alloc] initWithFrame:cell.contentView.bounds];
self.Name.placeholder= #"Name";
self.Name.autocorrectionType = UITextAutocorrectionTypeNo;
self.Name.textAlignment = NSTextAlignmentCenter;
self.Name.delegate = self;
[self.Name setValue:[UIColor whiteColor] forKeyPath:#"_placeholderLabel.textColor"];
[self.Name setTextColor:[UIColor whiteColor]];
[cell.contentView addSubview:self.Name];
[cell.contentView.layer setBorderColor:[UIColor whiteColor].CGColor];
}
else if (indexPath.section == 2)
{
self.Email = [[UITextField alloc] initWithFrame:cell.contentView.bounds];
self.Email.placeholder= #"Email";
self.Email.autocorrectionType = UITextAutocorrectionTypeNo;
self.Email.textAlignment = NSTextAlignmentCenter;
self.Email.delegate = self;
[self.Email setValue:[UIColor whiteColor] forKeyPath:#"_placeholderLabel.textColor"];
[self.Email setTextColor:[UIColor whiteColor]];
[cell.contentView addSubview:self.Email];
[cell.contentView.layer setBorderColor:[UIColor whiteColor].CGColor];
}
else if (indexPath.section == 3)
{
self.Password = [[UITextField alloc] initWithFrame:cell.contentView.bounds];
self.Password.placeholder= #"Password";
self.Password.autocorrectionType = UITextAutocorrectionTypeNo;
self.Password.textAlignment = NSTextAlignmentCenter;
self.Password.delegate = self;
[self.Password setValue:[UIColor whiteColor] forKeyPath:#"_placeholderLabel.textColor"];
[self.Password setTextColor:[UIColor whiteColor]];
[cell.contentView addSubview:self.Password];
[cell.contentView.layer setBorderColor:[UIColor whiteColor].CGColor];
}
else if (indexPath.section == 4)
{
self.RepetePassword = [[UITextField alloc] initWithFrame:cell.contentView.bounds];
self.RepetePassword.placeholder= #"Repeat password";
self.RepetePassword.autocorrectionType = UITextAutocorrectionTypeNo;
self.RepetePassword.textAlignment = NSTextAlignmentCenter;
self.RepetePassword.delegate = self;
[self.RepetePassword setValue:[UIColor whiteColor] forKeyPath:#"_placeholderLabel.textColor"];
[self.RepetePassword setTextColor:[UIColor whiteColor]];
[cell.contentView addSubview:self.RepetePassword];
[cell.contentView.layer setBorderColor:[UIColor whiteColor].CGColor];
}
else if (indexPath.section == 5)
{
cell.textLabel.text = #"Register";
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.textLabel.textColor = [UIColor whiteColor];
[cell.contentView.layer setBackgroundColor:[UIColor greenColor].CGColor];
[cell.contentView.layer setBorderColor:[UIColor clearColor].CGColor];
}
cell.backgroundColor = [UIColor clearColor];
cell.backgroundView = [UIView new];
cell.selectedBackgroundView = [UIView new];
[cell.contentView.layer setBorderWidth:1.0f];
[cell.contentView.layer setCornerRadius:20.0f];
[cell.contentView.layer setMasksToBounds:YES];
return cell;
}
The first thing is that you are allocating your uitextfield in cellForRowAtIndexPath method thats why they appears again and again when you are scrolling.Because nature of uitableview is do whatever developer want in visible cells not in the out of screen thats why when you scrolling this method calling again and again. Just try to allocate textfield in viewDidLoad method or somewhere else.
The second thing is to make them visible as you wanted, you may just use constraints center horizantically and vertically in uitableviewcell. To do that in UI just select your uitextfield hold the control key and drag it in that then click center horizanticall and vertically.
I hope these advices can solve your problems.
Related
this is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"hourCell" forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text=hoursarray[indexPath.row];
if ([cell.contentView subviews]){
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
}
UIButton *buttonOff = [UIButton buttonWithType:UIButtonTypeCustom];
buttonOff.layer.cornerRadius = 5.0f;
UIButton *buttonT1 = [UIButton buttonWithType:UIButtonTypeCustom];
buttonT1.layer.cornerRadius = 5.0f;
UIButton *buttonT2 = [UIButton buttonWithType:UIButtonTypeCustom];
buttonT2.layer.cornerRadius = 5.0f;
buttonOff.frame = CGRectMake(130, 5, 40, 34);
[buttonOff setTitle:#"OFF" forState:UIControlStateNormal];
[buttonOff addTarget:self action:#selector(onButtonOFFTap:) forControlEvents:UIControlEventTouchUpInside];
buttonT1.frame = CGRectMake(190, 5, 40, 34);
[buttonT1 setTitle:#"T1" forState:UIControlStateNormal];
[buttonT1 addTarget:self action:#selector(onButtonT1Tap:) forControlEvents:UIControlEventTouchUpInside];
buttonT2.frame = CGRectMake(250, 5, 40, 34);
[buttonT2 setTitle:#"T2" forState:UIControlStateNormal];
[buttonT2 addTarget:self action:#selector(onButtonT2Tap:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:buttonOff];
[cell.contentView bringSubviewToFront:buttonOff];
buttonOff.tag=indexPath.row;
[cell addSubview:buttonT1];
[cell.contentView bringSubviewToFront:buttonT1];
buttonT1.tag=indexPath.row;
[cell.contentView bringSubviewToFront:buttonT2];
[cell addSubview:buttonT2];
buttonT2.tag=indexPath.row;
if([[NSString stringWithFormat:#"%#",[datiProgrTemp objectAtIndex:indexPath.row+48*day]] isEqual:#"1"])
{
buttonOff.backgroundColor = [UIColor greenColor];
buttonT1.backgroundColor = [UIColor lightGrayColor];
buttonT2.backgroundColor = [UIColor lightGrayColor];
}
if([[NSString stringWithFormat:#"%#",[datiProgrTemp objectAtIndex:indexPath.row+48*day]] isEqual:#"2"])
{
buttonOff.backgroundColor = [UIColor lightGrayColor];
buttonT1.backgroundColor = [UIColor greenColor];
buttonT2.backgroundColor = [UIColor lightGrayColor];
}
if([[NSString stringWithFormat:#"%#",[datiProgrTemp objectAtIndex:indexPath.row+48*day]] isEqual:#"3"])
{
buttonOff.backgroundColor = [UIColor lightGrayColor];
buttonT1.backgroundColor = [UIColor lightGrayColor];
buttonT2.backgroundColor = [UIColor greenColor];
}
return cell;
}
The fact is that after two or three scrolls (fast and smooth) the scrolling goes slow and crappy and the ram used increase.
I tried to put if(cell==nill) but I'm using storyboard and the cell is never nill
Am I wrong in something?
Thanks a lot,
N.
There are a couple problems here.
The whole point of using dequeueReusableCellWithIdentifier: is to reuse your cells and their content. But I see you've used this line:
if ([cell.contentView subviews]){
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
}
to remove the cell content at every call to cellForRowAtIndexPath:. This is a waste of using dequeueReusableCellWithIdentifier:.
Nevertheless, your logic is almost correct. You can remove the subviews and create new subviews without having the incremental memory issues you're describing. The problem is you've made a small error:
You're adding the UIButtons directly to the cell's view, for example
[cell addSubview:buttonOff];
but removing the subviews of the cell's content view:
[cell.contentView subviews]
(You're also using bringSubviewToFront: ineffectively for this same reason.)
Because of this mistake, you're not actually removing the buttons at every call to cellForRowAtIndexPath: as you've intended so as you scroll back and forth, buttons are being added one on top of another on top of another, thus increasing memory usage.
To fix this problem, whether you add and remove from cell or cell.contentView, you have to be consistent.
All that aside though, since the content of your cells is very similar, I highly recommend you use dequeueReusableCellWithIdentifier: in the way it was intended by actually reusing your cells' content.
Thanks to all. This is the code working good. I added a TableViewCell class that contains only the outlet to the buttons (added buttons graphically in the storyboard):
#import <UIKit/UIKit.h>
#interface CHRTableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIButton *buttonOFF;
#property (weak, nonatomic) IBOutlet UIButton *buttonT1;
#property (weak, nonatomic) IBOutlet UIButton *buttonT2;
#end
then instantiated cell on tableview controller and pointing to the outlet changed the button's aspect:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CHRTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"hourCell" forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text=hoursarray[indexPath.row];
cell.buttonOFF.layer.borderColor = [UIColor lightGrayColor].CGColor;
cell.buttonOFF.layer.borderWidth = 0.5f;
cell.buttonOFF.layer.cornerRadius = 5.0f;
cell.buttonT1.layer.borderColor = [UIColor lightGrayColor].CGColor;
cell.buttonT1.layer.borderWidth = 0.5f;
cell.buttonT1.layer.cornerRadius = 5.0f;
cell.buttonT2.layer.borderColor = [UIColor lightGrayColor].CGColor;
cell.buttonT2.layer.borderWidth = 0.5f;
cell.buttonT2.layer.cornerRadius = 5.0f;
[cell.buttonOFF setTitle:#"OFF" forState:UIControlStateNormal];
[cell.buttonOFF addTarget:self action:#selector(onButtonOFFTap:) forControlEvents:UIControlEventTouchUpInside];
[cell.buttonT1 setTitle:#"T1" forState:UIControlStateNormal];
[cell.buttonT1 addTarget:self action:#selector(onButtonT1Tap:) forControlEvents:UIControlEventTouchUpInside];
[cell.buttonT2 setTitle:#"T2" forState:UIControlStateNormal];
[cell.buttonT2 addTarget:self action:#selector(onButtonT2Tap:) forControlEvents:UIControlEventTouchUpInside];
cell.buttonOFF.tag=indexPath.row;
cell.buttonT1.tag=indexPath.row;
cell.buttonT2.tag=indexPath.row;
if([[NSString stringWithFormat:#"%#",[datiProgrTemp objectAtIndex:indexPath.row+48*day]] isEqual:#"1"])
{
cell.buttonOFF.backgroundColor = [UIColor colorWithRed:0.0f/255.0f green:200.0f/255.0f blue:60.0f/255.0f alpha:1.0f];
cell.buttonT1.backgroundColor = [UIColor whiteColor];
cell.buttonT2.backgroundColor = [UIColor whiteColor];
}
if([[NSString stringWithFormat:#"%#",[datiProgrTemp objectAtIndex:indexPath.row+48*day]] isEqual:#"2"])
{
cell.buttonOFF.backgroundColor = [UIColor whiteColor];
cell.buttonT1.backgroundColor = [UIColor colorWithRed:0.0f/255.0f green:200.0f/255.0f blue:60.0f/255.0f alpha:1.0f];;
cell.buttonT2.backgroundColor = [UIColor whiteColor];
}
if([[NSString stringWithFormat:#"%#",[datiProgrTemp objectAtIndex:indexPath.row+48*day]] isEqual:#"3"])
{
cell.buttonOFF.backgroundColor = [UIColor whiteColor];
cell.buttonT1.backgroundColor = [UIColor whiteColor];
cell.buttonT2.backgroundColor = [UIColor colorWithRed:0.0f/255.0f green:200.0f/255.0f blue:60.0f/255.0f alpha:1.0f];;
}
return cell;
}
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"];
}
}
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...
I have app in which i am using tableView problem is that when tableView has one record then it does not show separator line but shows when there are two records.
The first cell in tableView is textField. here is the code i am using.
for (UIView *subView in cell.subviews)
{
if (subView.tag == 2 || subView.tag == 22)
{
[subView removeFromSuperview];
}
}
tableView.backgroundView=nil;
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
tableView.separatorInset = UIEdgeInsetsZero;
if(indexPath.section==0){
tagInputField =[[UITextField alloc]initWithFrame:CGRectMake(0,0,248,31)];
tagInputField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
tagInputField.textAlignment=UITextAlignmentLeft;
tagInputField.backgroundColor=[UIColor whiteColor];
tagInputField.tag = 2;
tagInputField.delegate = self;
tagInputField.clearButtonMode = UITextFieldViewModeWhileEditing;
[tagInputField.layer setCornerRadius:5.0f];
[tagInputField.layer setMasksToBounds:YES];
tagInputField.layer.borderWidth = 0.3;
tagInputField.layer.borderColor = [UIColor darkGrayColor].CGColor;
tagInputField.font=[UIFont fontWithName:#"Myriad-Pro" size:8];
[tagInputField setText:#"Enter tag here "];
tagInputField.textColor =[UIColor grayColor];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
[cell addSubview:tagInputField];
return cell;
}
if(indexPath.section==1) {
UIButton *crossButton =[[UIButton alloc]initWithFrame:CGRectMake(228, 8, 18, 18)];
crossButton.tag = 22; //use a tag value that is not used for any other subview
//crossButton.backgroundColor = [UIColor purpleColor];
crossButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"Cross.png"]];
[cell addSubview:crossButton];
cell.textLabel.font =[UIFont fontWithName:#"Myriad-Pro" size:8];
cell.textLabel.textColor =[UIColor grayColor];
cell.backgroundColor=[UIColor whiteColor];
cell.textLabel.text =[tagArray objectAtIndex:indexPath.row];
[crossButton addTarget:self action:#selector(deleteCell:) forControlEvents:UIControlEventTouchUpInside];
[tagInputField setFrame:CGRectMake(5,0,248,31)];
tableView.backgroundColor=[UIColor whiteColor];
[tagInputField.layer setCornerRadius:0.0f];
[tagInputField.layer setMasksToBounds:YES];
tagInputField.layer.borderWidth = 0.0;
tagInputField.layer.borderColor = [UIColor clearColor].CGColor;
return cell;
}
When you will have only 1 record then separator will not show, and you should setting the separator for tableView at viewDidLoad look like
- (void)viewDidLoad
{
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
and in any case you want to show your own separator for every single cell ten try to add a imageView or somrthing witch share by the table cell
UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 1024, 1)];
separatorView.layer.borderColor = [UIColor redColor].CGColor;
separatorView.layer.borderWidth = 1.0;
[cell.contentView addSubview:separatorView];
How to customize tableView separator in iPhone
go for more on it....
Just try like this in side the Cell_for_Row_At_Index_path delegate method:
[tableView setSeparatorInset:UIEdgeInsetsZero];
[tableView setSeparatorColor:[UIColor greenColor]];
just paste this line and check.
add an empty footer at the end of the tableview to show the separator. To do so implement the following tableview delegate method in your class with your other tableview delegate functions:
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
return 0.001;
}
I used this to add last cell separator line....
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 1.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
// To "clear" the footer view
UIView *separatorLine = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 1024, 1)];
separatorLine.layer.borderColor = [UIColor grayColor].CGColor;
separatorLine.layer.borderWidth = 1.0;
return separatorLine;
}
I found none of the above answers worked. I was particularly wary of the answer suggesting adding a UIView to look like the line.
In the end I found that this answer worked for me:
tableView.separatorStyle= UITableViewCellSeparatorStyleSingleLine;
In another answer it was suggested that adding worked better
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
tableView.separatorStyle= UITableViewCellSeparatorStyleSingleLine;
but I found that this was unnecessary.
All the credit goes to user859045 and samvermette for their answers on different threads. samvermette's thread especially has a lot of answers on this topic which are very helpful and worth a look.
I am trying to use the function sizeToFit. It works perfectly throughout the application however it does not work in the code below. Further to that, if it can't be done the way I am doing it please advise.
self.label = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 67.0, 290, 50)];
self.label.font= [UIFont fontWithName:#"Helvetica-Bold" size:20];
self.label.textColor = [UIColor colorWithRed:33.0f/255.0f green:74.0f/255.0f blue:146.0f/255.0f alpha:1.0f];
self.label.numberOfLines = 0;
self.label.lineBreakMode = NSLineBreakByWordWrapping;
self.label.backgroundColor = [UIColor whiteColor];
[self.contentView addSubview:self.label];
self.description = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 380.0, 300, 400)];
self.description.font= [UIFont fontWithName:#"Helvetica-Light" size:15];
self.description.textColor = [UIColor blackColor];
self.description.textAlignment = NSTextAlignmentJustified;
self.description.numberOfLines = 0;
self.description.lineBreakMode = NSLineBreakByWordWrapping;
self.description.backgroundColor = [UIColor whiteColor];
[self.description sizeToFit];
[self.contentView addSubview:self.description];
self.image = [[UIImageView alloc] initWithFrame:CGRectMake(20, 130, 280, 228)];
self.image.clipsToBounds = YES;
//[scrollView addSubview:self.image];
[self.contentView addSubview:self.image];
self.backgroundColor = [UIColor whiteColor];
I passed the data using this method from a different controller
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
Cell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
NSDictionary *item = [_articleListmain objectAtIndex:indexPath.item];
// set the article image
[cell.image setImageWithURL:[item objectForKey:#"image"]];
[cell.label setText:[item objectForKey:#"title"]];
[cell.description setText:[item objectForKey:#"description"]];
return cell;
}
Since the label is empty, sizeToFit shrinks it down to nothing. That's the point. Set some text then call sizeToFit and the label will be just big enough for the text.
I encountered the same problem. I have a customized cell and a separated tableview controller. it turns out that we should set the NumberOfLines and SizeToFit in the controller, not the cell.