I have UITableViewCell and inside that I have UITextfield, I made 7 sections (dynamic) and each section have one cell (one row) which includes UITextField .
Now I have one button on right top corner of UINavigationBar (EDIT button).
I need to enable user interaction enable for all section textfields . Hows that possible?
This is my UITableviewCode
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
sharedManager=[Mymanager sharedManager];
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//UITableViewCell *cell;
UILabel *label = nil;
NSString *text;
cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil)
{
cell = [[timeLineDetailsCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"cell"];
label = [[UILabel alloc] initWithFrame:CGRectZero];
[label setLineBreakMode:UILineBreakModeWordWrap];
[label setMinimumFontSize:FONT_SIZE];
[label setNumberOfLines:0];
[label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
[label setTag:1];
[[label layer] setBorderWidth:2.0f];
[[cell contentView] addSubview:label];
}
if(indexPath.section==0){
text = [contents objectAtIndex:0];
}else if(indexPath.section==1){
text = [contents objectAtIndex:1];
}else if(indexPath.section==2){
text = [contents objectAtIndex:2];
}else if(indexPath.section==3){
text = [contents objectAtIndex:3];
}else if(indexPath.section==4){
text = [contents objectAtIndex:4];
}else if(indexPath.section==5){
text = [contents objectAtIndex:5];
}else if(indexPath.section==6){
text = [contents objectAtIndex:6];
}else if(indexPath.section==7){
text = [contents objectAtIndex:7];
}
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
if (!label)
label = (UILabel*)[cell viewWithTag:1];
[cell.ds1 setText:text];
[cell.ds1 setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *text ;
if(indexPath.section==0){
text = [contents objectAtIndex:0];
}else if(indexPath.section==1){
text = [contents objectAtIndex:1];
}else if(indexPath.section==2){
text = [contents objectAtIndex:2];
}else if(indexPath.section==3){
text = [contents objectAtIndex:3];
}else if(indexPath.section==4){
text = [contents objectAtIndex:4];
}else if(indexPath.section==5){
text = [contents objectAtIndex:5];
}else if(indexPath.section==6){
text = [contents objectAtIndex:6];
}else if(indexPath.section==7){
text = [contents objectAtIndex:7];
}
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 44.0f);
return height + (CELL_CONTENT_MARGIN * 2);
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *str= [title objectAtIndex:section];
return str;
}
my edit button code is
-(void)editTimeline{
cell.ds1.userInteractionEnabled=YES;
[cell.ds1 setUserInteractionEnabled:TRUE];
cell.ds1.layer.borderColor=[UIColor lightGrayColor].CGColor;
cell.ds1.layer.borderWidth=1;
// [cell.ds1 becomeFirstResponder];
}
when i click on EDIT button only some rows are able to edit .please help me .
define flag data memeber with Bool type
-(void)editTimeline{
flag=true;
[self.tableView reload];
}
add following condition in cellForRowAtIndexpath method
if(flag==true){
[cell.ds1 setUserInteractionEnabled:TRUE];
}
else{
[cell.ds1 setUserInteractionEnabled:NO];
}
let me know if it help u....!!!
I would use this code -
NSArray *cellArray=[itemsTable visibleCells];
for (UITableViewCell *aCell in cellArray)
{
UITextField *myTField=(UITextField*)yourtextField;
myTField.userInteractionEnabled=YES;
}
myTField is added on cell as a subView with specific tag. You can get the myTField via [aCell viewWithTag:someTag];.
Call cellForRowAtIndexPath for each row in your section, make it unselectable by the tableView (otherwise it will triger the tap instead of you) and enable user interactions in the way you want for you returned cell :3
Related
I need to create a simple chat view in which i can show messages from two ends (sender and receiver) like any Message App .
What i have done till now is , created a UITableView , A UIButton and a UITextField. And on that UIButton tap , i am adding UITextField text to array , Now I need the second end also like in ours Messaging app (sender side).
Left side is receiver and Right side is sender.
My app till now looks like
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
messageLabel = nil;
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
messageLabel = [[UILabel alloc] init];
messageLabel.tag = 101;
[cell.contentView addSubview: messageLabel];
} else {
messageLabel = (UILabel*)[cell.contentView viewWithTag: 101];
} //---calculate the height for the label---
int labelHeight = [self labelHeight:[listOfMessages objectAtIndex:indexPath.row]];
labelHeight -= bubbleFragment_height;
if (labelHeight<0) labelHeight = 0;
messageLabel.frame =
CGRectMake(bubble_x + 10, bubble_y + 5,
(bubbleFragment_width * 3) - 25,
(bubbleFragment_height * 2) + labelHeight - 10);
messageLabel.font = [UIFont systemFontOfSize:15];
messageLabel.textAlignment = NSTextAlignmentCenter;
messageLabel.textColor = [UIColor darkTextColor];
messageLabel.backgroundColor = [UIColor greenColor];
messageLabel.numberOfLines = 0;
messageLabel.layer.cornerRadius = 8;
messageLabel.layer.masksToBounds = YES;
messageLabel.text = [listOfMessages objectAtIndex:indexPath.row];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
-(void) sendAction:(id) sender {
[listOfMessages addObject:field.text];
[chatTable reloadData];
field.text = #"";
[field resignFirstResponder];
}
You can take two different custom cells one for the sender and one for the receiver like this:
for Sender
for Receiver
Now, in your app, there must be login and sign-up process as it is a chat app and there will be server associated with your app to save data.
What you can do is that, when you send the message, also send the name of the receiver with it and store it in your database.
Now, in your chat view, fetch all the message data, along with the receiver names.
Fetch the userName who is currently logged in during the Login process.
You can do something like this in your cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *myArrayElement = [arr_receiverUserName objectAtIndex:indexPath.row];
//do something useful with myArrayElement
if(![myArrayElement isEqualToString:userName])
{
/// These are my messages.
//// Pop up 'mycell' here
UILabel *lbl_myText = [[UILabel alloc]initWithFrame:CGRectZero];
[lbl_myText setLineBreakMode:NSLineBreakByWordWrapping];
lbl_myText.minimumScaleFactor = FONT_SIZE;
[lbl_myText setNumberOfLines:0];
lbl_myText.textAlignment = NSTextAlignmentRight;
[lbl_myText setFont:[UIFont systemFontOfSize:FONT_SIZE]];
NSString *text = [arr_text objectAtIndex:indexPath.row];
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]];
// Checks if text is multi-line
if (size.width > lbl_myText.bounds.size.width)
{
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
[lbl_myText setText:text];
[lbl_myText setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - cell.imgv_myImage.frame.size.width -(CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
}
else
{
lbl_myText.frame = CGRectMake(10, 0, cell.frame.size.width - cell.imgv_myImage.frame.size.width - 18,18);
lbl_myText.textAlignment = NSTextAlignmentRight;
[lbl_myText setText:text];
}
//lbl_myText.backgroundColor = [UIColor greenColor];
[cell.contentView addSubview:lbl_myText];
}
else
{
//// These are the messages sent by some one else
/// Pop up `someonecell` here
UILabel *lbl_myText = [[UILabel alloc]initWithFrame:CGRectZero];
[lbl_myText setLineBreakMode:NSLineBreakByWordWrapping];
lbl_myText.minimumScaleFactor = FONT_SIZE;
[lbl_myText setNumberOfLines:0];
lbl_myText.textAlignment = NSTextAlignmentLeft;
[lbl_myText setFont:[UIFont systemFontOfSize:FONT_SIZE]];
NSString *text = [arr_text objectAtIndex:indexPath.row];
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]];
// Checks if text is multi-line
if (size.width > lbl_myText.bounds.size.width)
{
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
[lbl_myText setText:text];
[lbl_myText setFrame:CGRectMake(cell.imgv_someoneImage.frame.size.width+8, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - cell.imgv_someoneImage.frame.size.width -(CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
}
else
{
lbl_myText.frame = CGRectMake(10, 0, cell.frame.size.width - cell.imgv_someoneImage.frame.size.width - 18,18);
lbl_myText.textAlignment = NSTextAlignmentLeft;
[lbl_myText setText:text];
}
//lbl_myText.backgroundColor = [UIColor greenColor];
[cell.contentView addSubview:lbl_myText];
}
You can do similar things for images and audios.
For Dynamic Height Of The Cell:
To make to the height of your cell according to your UILabels, refer to Increase the main tableview row height according to the custom cell
You need to create multiple cell with different CellIdentifier For Example. Cell For sender and receiver. And you can subdivide it in categories like text,audio,video,image.
Download sample ChatUI Demo (Objective-C & Swift) from here
Lets have example for the text chat.
First of all you need to create 2 cell prototypes in your Storyboard or XIB with different CellIdentifier for example "cellSender" and "cellReceiver".
Take UILabel or UITextView inside cell and for cellSender make left alignment and for cellReceiver make the alignment right for making different layout for sender and receiver.
Then You can do with following with your code...
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
BOOL sender = NO;
// Check for the sender or receiver
<code for checking message is from sender or receiver>
static NSString *CellIdentifier = sender?#"cellSender":#"cellReceiver";
messageLabel = nil;
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
messageLabel = [[UILabel alloc] init];
messageLabel.tag = 101;
[cell.contentView addSubview: messageLabel];
} else {
messageLabel = (UILabel*)[cell.contentView viewWithTag: 101];
} //---calculate the height for the label---
int labelHeight = [self labelHeight:[listOfMessages objectAtIndex:indexPath.row]];
labelHeight -= bubbleFragment_height;
if (labelHeight<0) labelHeight = 0;
messageLabel.frame =
CGRectMake(bubble_x + 10, bubble_y + 5,
(bubbleFragment_width * 3) - 25,
(bubbleFragment_height * 2) + labelHeight - 10);
messageLabel.font = [UIFont systemFontOfSize:15];
messageLabel.textAlignment = NSTextAlignmentLeft;
messageLabel.textColor = [UIColor darkTextColor];
messageLabel.backgroundColor = sender? [UIColor greenColor]: [UIColor lightGrayColor];
messageLabel.numberOfLines = 0;
messageLabel.layer.cornerRadius = 8;
messageLabel.layer.masksToBounds = YES;
messageLabel.text = [listOfMessages objectAtIndex:indexPath.row];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
EDIT
Hi i am beginner in Ios in my project i have added UItextView on UItableview cell and based on textlength automatically UItextview and UItableview cell height need to increase but according to my code all textdata not displayed on textview some data is missing please help me some one
This is my code:
formulaArray = [NSArray arrayWithObjects:#"Implement exponential back-off in your retry mechanism. (e.g. if you waited one second before the first retry,Implement exponential back-off in your retry mechanism. (e.g. if you waited one second before the first retry,Implement exponential back-off in your retry mechanism. (e.g. if you waited one second before the first retry,Implement exponential back-off in your retry mechanism. (e.g. if you waited one second before the first retry,finally",nil];
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cellIdentifier";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
if(indexPath.section == 1)
{
formulaText = [[UITextView alloc]init];
formulaText.font = [UIFont fontWithName:#"Bitter-Regular" size:15.0f];
formulaText.translatesAutoresizingMaskIntoConstraints = NO;
formulaText.backgroundColor = [UIColor lightGrayColor];
formulaText.scrollEnabled = NO;
[cell.contentView addSubview:formulaText];
NSDictionary * views = NSDictionaryOfVariableBindings(formulaText);
NSArray * formulaH = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-10-[formulaText]-10-|"
options:0
metrics:nil
views:views];
NSArray * formulaV = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-5-[formulaText]-5-|"
options:0
metrics:nil
views:views];
[cell.contentView addConstraints:formulaH];
[cell.contentView addConstraints:formulaV];
formulaText.text = [formulaArray objectAtIndex:0];
#define kMaxHeight 100.f
formulaText.contentSize = [formulaText.text sizeWithFont:[UIFont fontWithName:#"Bitter-Regular" size:15.0]
constrainedToSize:CGSizeMake(100, kMaxHeight)
lineBreakMode:NSLineBreakByWordWrapping];
}
if (indexPath.section == 2)
{
aboutText = [[UITextView alloc]init];
aboutText.font = [UIFont fontWithName:#"Bitter-Regular" size:15.0f];
aboutText.translatesAutoresizingMaskIntoConstraints = NO;
aboutText.backgroundColor = [UIColor darkGrayColor];
aboutText.scrollEnabled = NO;
[cell.contentView addSubview:aboutText];
NSDictionary * views = NSDictionaryOfVariableBindings(aboutText);
NSArray * formulaH = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-10-[aboutText]-10-|"
options:0
metrics:nil
views:views];
NSArray * formulaV = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-5-[aboutText]-5-|"
options:0
metrics:nil
views:views];
[cell.contentView addConstraints:formulaH];
[cell.contentView addConstraints:formulaV];
aboutText.text = [aboutArray objectAtIndex:0];
#define kMaxHeight 100.f
aboutText.contentSize = [aboutText.text sizeWithFont:[UIFont fontWithName:#"Bitter-Regular" size:15.0]
constrainedToSize:CGSizeMake(100, kMaxHeight)
lineBreakMode:NSLineBreakByWordWrapping];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//return 200;
if([indexPath section] == 0)
{
return 200;
}
else if([indexPath section] == 1)
{
NSString *cellText = [formulaArray objectAtIndex:0];
UIFont *cellFont = [self fontForCell];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
return labelSize.height + 20;
}
else
{
NSString *cellText = [aboutArray objectAtIndex:0];
UIFont *cellFont = [self fontForCell];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
return labelSize.height + 20;
}
}
But here formula array all text data is not displaying please help me some one
Try this.
- (CGSize )getLabelSizeForString:(NSString *)message withLabel:(UILabel *)label{
CGSize size = [message sizeWithFont:label.font constrainedToSize:CGSizeMake(label.bounds.size.width, 99999) lineBreakMode:NSLineBreakByWordWrapping];
return size;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CustomCell"];
NSString *message = [[self.dataArray objectAtIndex:indexPath.row]valueForKey:Message];
CGSize size = [[GlobalConstants sharedInstance] getLabelSizeForString:message withLabel:cell.aboutLabel];
return size.height;
}
or you may reffer the link
http://www.fantageek.com/1468/ios-dynamic-table-view-cells-with-varying-row-height-and-autolayout/
I think this function
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
is deprecated in your height ForRowAtIndexPath.
Try to use NSFontAttribute instead of it. In your case it looks like something like that:
CGRect textRect = [cellText boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:cellFont}
context:nil];
CGSize labelSize = textRect.size;
If you would like to increase it dynamically you need to refresh a specific cell edited. In your
- (void)textViewDidChange:(UITextView *)textView
You need to refresh your cell.
[tableView reloadRowsAtIndexPaths:#[yourIndex] withRowAnimation:UITableViewRowAnimationNone];
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return formulaArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
cell.myTextView.text = formulaArray[indexPath.row];
[cell.contentView layoutIfNeeded];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
You can easily implement these by storyboard.
Drag textview in the cell and add top, bottom, leading and trailing constraint only.
Uncheck scrolling enabled for textview.
then implement these methods
I have a label in a TableViewCell in which there are more than one lines of text. Initially on the label it shows only one line. I have a button on that cell. I want to expand the cell by clicking on the button upto the hight of the label's text.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"tabCell";
_cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSManagedObject *device = [self.persons objectAtIndex:indexPath.row];
UILabel *nameLabel = (UILabel*)[_cell.contentView viewWithTag:2];
nameLabel.text = [NSString stringWithFormat:#"%#", [device valueForKey:#"name"]];
UILabel *dateLabel = (UILabel *)[_cell.contentView viewWithTag:3];
dateLabel.text = [NSString stringWithFormat:#"%#",[device valueForKey:#"date"]];
UILabel *descLabel = (UILabel *)[_cell.contentView viewWithTag:4];
//descTextView.text = [NSString stringWithFormat:#"%#",[device valueForKey:#"desc"]];
UIImageView *personImage = (UIImageView *)[_cell.contentView viewWithTag:1];
UIImage *personImg = [UIImage imageWithData:[device valueForKey:#"image"]];
personImage.image = personImg;
UIButton *viewMoreButton = (UIButton *)[_cell.contentView viewWithTag:5];
[viewMoreButton addTarget:self
action:#selector(myAction)
forControlEvents:UIControlEventTouchUpInside];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:[device valueForKey:#"desc"]
attributes:#{ NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue" size:17]}];
reqFrame=[attrString boundingRectWithSize:CGSizeMake(descLabel.frame.size.height, CGFLOAT_MAX)options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
descLabel.attributedText = attrString;
return _cell;
}
- (void)myAction{
//what to write here?
}
First of all it is not a good practice to build cell in cellForRowAtIndexPath. Use willDisplayCell instead. See here why.
Secondly to do what you want you have to set desired height in heightForRowAtIndexPath. Once this accomplished, within your button selector call to refresh specific cells using
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
The implementation is similar:
- (void)buttonSelector
{
myLabel.text = #"YOUR TEXT";
[myLabel sizeToFit];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
...
return yourLabel.height;
}
Anyhow need to get reference of the cell and indexPath on which the button is tapped in your myAction().
Create a private variable CGFloat newCellHeight; and initialize it to 0.0.
Let reference to the associated cell is selectedCell and selected index path is indexPathOfTappedCell.
- (void)myAction{
UILabel *descLabel = (UILabel*)[selectedCell.contentView viewWithTag:4];
[descLabel sizeToFit]; // Automatically increases the height of the label as required
newCellHeight = CGRectGetMaxY(descLabel.frame) + 10.0; // Extra padding 10.0
[tableView reloadRowsAtIndexPaths:#[indexPathOfTappedCell] withRowAnimation:UITableViewRowAnimationAutomatic];
}
Now add the following TableView delegate method in your view controller
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.section == indexPathOfTappedCell.section &&
indexPath.row == indexPathOfTappedCell.row ) {
return newCellHeight;
}
return 44.0; // Suppose default height is 44.0
}
you need to maintain two variables, just give tag to your button, and detect in action by its tag to reload that particular cell and another BOOL variable to detect if button touched. You should calculate height in heightForRowAtIndexPath method. I am posting code, it may help you
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if(isReadMoreButtonTouched && [indexPath row]== indexOfReadMoreButton) {
NSString *yourText = [arr1 objectAtIndex:indexPath.row]; // your text
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"Avenir Next" size:14], NSFontAttributeName,
[UIColor grayColor], NSForegroundColorAttributeName,
nil]; // set custom attributes
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:yourText attributes:attributes];
CGRect paragraphRect = [attributedText boundingRectWithSize:CGSizeMake(625, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil]; //here 625 is width of label
NSLog(#"height = %f", paragraphRect.size.height);
return paragraphRect.size.height;
}
else{
return 200; //default height taken in storyboard
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
cell.lblKB.text = [arr objectAtIndex:indexPath.row];
cell.lblDetail.text = [arr1 objectAtIndex:indexPath.row];
NSString *yourText = [arr1 objectAtIndex:indexPath.row];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"Avenir Next" size:14], NSFontAttributeName,
GrayColor, NSForegroundColorAttributeName,
nil]; //your custom attributes
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:yourText attributes:attributes];
CGRect paragraphRect = [attributedText boundingRectWithSize:CGSizeMake(625, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil];
NSLog(#"height = %f", paragraphRect.size.height);
if (paragraphRect.size.height<200) {
cell.btnMore.hidden = YES;
}
else{
cell.btnMore.hidden = NO;
}
cell.btnMore.tag = indexPath.row;
return cell;
}
// action of button click
-(IBAction)MoreBtnClicked:(id)sender {
if (!isReadMoreButtonTouched) {
isReadMoreButtonTouched = YES;
}
else{
isReadMoreButtonTouched = NO;
}
indexOfReadMoreButton = [sender tag];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[sender tag] inSection:0];
[self.tblKB reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; //reload that cell of your tableview
}
I am creating UITableView, where each cell size will b calculated based on the text I input.
I am Calculating size of Cell in heighForRowAtIndexPath
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *text = [tableData objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(210.0f, 20000.0f);
size = [text sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
height = MAX(size.height, 44.0f);
return height + (CCM * 2);
}
this is how I am calculating height for each cell, now my question is - I want to add image to each cell like comment box? like this
Click here to see comment boxes I am looking for
You can see these kind of comment boxes
what I did is I made my image into two parts
first one has top part which is working well on every cell starting image is coming
now while fixing bottom part me facing problem
for small text in cell UILable its working well
when size of text in UILabel increased it's not getting properly adjusted
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = #"cell";
NSLog(#"index path %d", indexPath.row);
MyTableCell *cell = (MyTableCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil)
{
cell = [[[MyTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
[cell.cellBackgroundBottom setFrame:CGRectMake(75.0f, 92.0f, 228.0f, height + 25.0f)];
[cell.cellContent setText:(NSString*)[tableData objectAtIndex:[indexPath row]]];
[cell.cellContent sizeToFit];
CGRect theFrame = [cell.cellContent frame];
theFrame.size.width = 210.0f;
[cell.cellContent setFrame: theFrame];
return cell;
}
I have created one UITableView subclass naming MYTableCell where I have defined what all I need inside my each cell.
// Creating UILabel for cell content or comments block
cellContent = [[UILabel alloc]initWithFrame: CGRectMake( 90.0f, 15.0f, 210.0f, 60.0f)] ;
[cellContent setLineBreakMode:UILineBreakModeWordWrap];
cellContent.numberOfLines = 0;
[cellContent setMinimumFontSize:15.0f];
[cellContent setBackgroundColor:[UIColor clearColor]];
// [cellContent setTextColor:[UIColor colorWithRed:73.0f green:73.0f blue:73.0f alpha:1.0f]];
[cellContent setFont:[UIFont fontWithName:#"Helvetica" size:12.0f]];
cellContent.textAlignment = UITextAlignmentLeft;
[cellContent setTag:1];
[self addSubview:cellContent];
[cellContent release];
cellBackgroundTop = [[UIImageView alloc] initWithFrame:CGRectMake(60.0f, 5.0f, 243.0f, 13.5f)];
[cellBackgroundTop setImage:[UIImage imageNamed:#"comments.png"]];
[self addSubview:cellBackgroundTop];
[cellBackgroundTop release];
cellBackgroundBottom = [[UIImageView alloc] initWithFrame:CGRectZero];
[cellBackgroundBottom setImage:[UIImage imageNamed:#"Untitled-1_09.png"]];
[self addSubview:cellBackgroundBottom];
[cellBackgroundBottom release];
I got answer for my question
. This is what i have to do in my cellForRowAtIndexPath
NSString *text = [tableData objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(210.0f, 20000.0f);
CGSize size1 = [text sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height1 = MAX(size1.height, 44.0f);
[cell.cellBackgroundBottom setFrame:CGRectMake(75.0f, 18.0f, 228.0f, height1 + 10.0f)];
i've implemented, in my iOS ap, some TdBadgedCell (from https://github.com/tmdvs/TDBadgedCell) in a UITabView. But when I want to manage the cells' hight dynamically by using something like this example:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *text = [items objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 44.0f);
return height + (CELL_CONTENT_MARGIN * 2);
}
the cell's width is the entire width of the cell (calculated variable "constraint" in the example below) and not the real width of the label printed on screen taking consideration of the badge's width. So, the portion of text at the end of the UILabel doesn't appear in cell when the text in too long.
How can I resolve this please?
I've solved my own problem with this portions of code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
MyObject *obj = [self.myObjects objectAtIndex:indexPath.row];
NSString *textlabel = [self getMainTextStringFromMyObject:obj];
NSString *detailtextlabel = [self getDetailTextStringFromMyObject:obj];
CGFloat height = MAX(CELL_TEXTLABEL_HEIGHT + [self getDetailTextSizeForString:detailtextlabel].height, CELL_ROW_DEFAULTHEIGHT);
return height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
MyObject *obj = [self.myObjects objectAtIndex:indexPath.row];
NSString *textlabel = [self getMainTextStringFromMyObject:obj];
NSString *detailtextlabel = [self getDetailTextStringFromMyObject:obj];
static NSString *CellIdentifier = #"ImageOnRightCell";
UILabel *mainLabel, *secondLabel;
UIImageView *photo;
TDBadgedCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(CELL_LABELS_MARGIN, 1.0, CELL_TEXTLABEL_WIDTH, CELL_TEXTLABEL_HEIGHT)] autorelease];
mainLabel.tag = MAINLABEL_TAG;
mainLabel.font = [UIFont boldSystemFontOfSize:CELL_TEXTLABEL_FONTSIZE];
mainLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:mainLabel];
secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(CELL_LABELS_MARGIN, CELL_TEXTLABEL_HEIGHT, CELL_TEXTLABEL_WIDTH, 19.0)] autorelease];
secondLabel.tag = SECONDLABEL_TAG;
secondLabel.font = [UIFont systemFontOfSize:CELL_DETAILTEXTLABEL_FONTSIZE];
secondLabel.textColor = [UIColor darkGrayColor];
secondLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
secondLabel.numberOfLines = 0;
secondLabel.lineBreakMode = UILineBreakModeWordWrap;
[cell.contentView addSubview:secondLabel];
float yOriginImg = (cell.contentView.frame.size.height/2.0);
if((CELL_TEXTLABEL_HEIGHT + [self getDetailTextSizeForString:detailtextlabel].height) <= CELL_ROW_DEFAULTHEIGHT)
{
yOriginImg -= (CELL_IMGHEIGHT/2.0);
}
photo = [[[UIImageView alloc] initWithFrame:CGRectMake(CELL_LABELS_MARGIN+CELL_TEXTLABEL_WIDTH, yOriginImg, CELL_IMGWIDTH, CELL_IMGHEIGHT)] autorelease];
photo.tag = PHOTO_TAG;
[cell.contentView addSubview:photo];
}
else
{
mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
photo = (UIImageView *)[cell.contentView viewWithTag:PHOTO_TAG];
}
mainLabel.text = textlabel;
secondLabel.text = detailtextlabel;
cell.badgeString = [NSString stringWithFormat:#"%g",obj.duration];
UIImage *theImage = [UIImage imageNamed:#"right_cell_icon.png"];
photo.image = theImage;
return cell;
}
- (NSString*) getMainTextStringFromMyObject:(MyObject*) obj
{
return obj != nil? obj.name : nil;
}
- (NSString*) getDetailTextStringFromMyObject:(MyObject*) obj
{
return obj.detail != nil ? obj.detail : nil;
}
- (CGSize) getDetailTextSizeForString:(NSString*) str
{
CGSize constraint = CGSizeMake(CELL_TEXTLABEL_WIDTH - (CELL_LABELS_MARGIN * 2), 20000.0f);
return [str sizeWithFont:[UIFont systemFontOfSize:CELL_DETAILTEXTLABEL_FONTSIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
}