Ton*_*ony 42 iphone uitableview uitextview
我希望有一个类似于Apple的iPhone Contacts应用程序的行为视图:内置uitextview的uitableviewcell,因此当我在uitextview中写入时,uitextview会增加其高度,因此uitableviewcell会动态调整其高度.我在整个网络上搜索,只找到部分解决方案,缺少示例代码!
请帮帮我,我很绝望
托尼
Aja*_*rma 37
看看这个,你需要有点棘手.您需要动态计算textView的高度,并根据TextView的高度,您需要返回单元格的高度.
这很简单,有点棘手......
这是您可以通过它来计算字符串大小的代码....
首先得到String的大小
NSString *label = @"Sample String to get the Size for the textView Will definitely work ";
CGSize stringSize = [label sizeWithFont:[UIFont boldSystemFontOfSize:15]
constrainedToSize:CGSizeMake(320, 9999)
lineBreakMode:UILineBreakModeWordWrap];
over here ....
NSLog(@"%f",stringSize.height);
Run Code Online (Sandbox Code Playgroud)
其次,在单元格中动态创建textView ..使用stringSize.height
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//}
NSDictionary *d=(NSDictionary *)[self.menuArray objectAtIndex:indexPath.section];
NSString *string = [d valueForKey:@"Description"];
CGSize stringSize = [string sizeWithFont:[UIFont boldSystemFontOfSize:15] constrainedToSize:CGSizeMake(320, 9999) lineBreakMode:UILineBreakModeWordWrap];
UITextView *textV=[[UITextView alloc] initWithFrame:CGRectMake(5, 5, 290, stringSize.height+10)];
textV.font = [UIFont systemFontOfSize:15.0];
textV.text=string;
textV.textColor=[UIColor blackColor];
textV.editable=NO;
[cell.contentView addSubview:textV];
[textV release];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *d=(NSDictionary *)[self.menuArray objectAtIndex:indexPath.section];
NSString *label = [d valueForKey:@"Description"];
CGSize stringSize = [label sizeWithFont:[UIFont boldSystemFontOfSize:15]
constrainedToSize:CGSizeMake(320, 9999)
lineBreakMode:UILineBreakModeWordWrap];
return stringSize.height+25;
}
Run Code Online (Sandbox Code Playgroud)
在给我的手指带来如此多的痛苦之后......我认为这是足够的代码......并且肯定会有助于解决你的问题..
祝好运
Tom*_*ift 11
创建一个自定义UITableViewCell并将您的UITextView添加到单元格的contentView.
在LayoutSubviews中,将textView.frame设置为单元格的contentView.bounds(或执行其他一些自定义布局).
当textView内容更改(通过UITextViewDelegate发现)时,请执行以下两项操作:
1)调用[tableView beginUpdates]; [tableView endUpdates];
这将强制表视图重新计算所有单元格的高度(将调用tableView:heightForRowAtIndexPath:
).如果您的单元格是textView的委托,那么您将必须弄清楚如何获取指向tableView的指针,但有几种方法可以实现.或者你可以让委托你的视图控制器......
2)当tableView:heightForRowAtIndexPath:
为这个细胞调用时,返回textView.contentSize.height
.你可以通过调用来获取你的单元格.[tableView cellForRowAtIndexPath];
如果你只有这些单元格中的一个,那么在viewController中缓存指向它的指针.