将imageview添加为uitableviewcell的子视图时如何使imageview可拉伸
Posted
技术标签:
【中文标题】将imageview添加为uitableviewcell的子视图时如何使imageview可拉伸【英文标题】:How to make imageview as stretchable when imageview is added as subview of uitableviewcell 【发布时间】:2013-05-30 13:58:40 【问题描述】:如果我在表格单元格中写多于两行,我想让 imageview 具有可拉伸性。 代码如下:
如有任何帮助,将不胜感激。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
chatCell *cell = (chatCell *)[tableView dequeueReusableCellWithIdentifier:CHAT_CELL_IDENTIFIER];
NSUInteger row = indexPath.row;
if (row < chatData.count)
self.bubbleImage = [[UIImageView alloc] init];
self.bubbleImage.frame = CGRectMake(0,22,250,66);
self.bubbleImage.image = [[UIImage imageNamed:@"bubbleMine.png"] stretchableImageWithLeftCapWidth:21 topCapHeight:14];
NSString *chatText = [[chatData objectAtIndex:row] objectForKey:TEXT];
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
UIFont *font = [UIFont systemFontOfSize:14];
CGSize size = [chatText sizeWithFont:font constrainedToSize:CGSizeMake(150.0f, 1000.0f) lineBreakMode:NSLineBreakByCharWrapping];
cell.textString.frame = CGRectMake(75, 18, size.width +20, size.height + 20); // set text frame
cell.textString.font = [UIFont fontWithName:FONT_NAME size:FONT_SIZE]; // set text font
cell.textString.text = chatText; // set text
[cell.textString sizeToFit];
NSDate *theDate = [[chatData objectAtIndex:row] objectForKey:DATE];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:DATE_FORMAT];
NSString *timeString = [formatter stringFromDate:theDate];
cell.timeLabel.text = timeString; // set timeLabel to display date and time
cell.userLabel.text = [[chatData objectAtIndex:row] objectForKey:NAME]; // set userLabel to display userName
[self.bubbleImage addSubview:cell.userLabel];
[self.bubbleImage addSubview:cell.timeLabel];
[self.bubbleImage addSubview:cell.textString];
[cell addSubview:self.bubbleImage];
return cell;
任何帮助将不胜感激
【问题讨论】:
请注意,这个问题与 Xcode 没有任何关系。 【参考方案1】:你需要调整bubbleImage的框架高度。尝试利用单元格内textString的最大Y来计算bubbleImage的最终高度:
self.bubbleImage.frame = CGRectMake(0,22,250,CGRectGetMaxY(cell.textString.frame)+10.0);
还记得计算表格视图单元格每一行的高度。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//calculate your height for each row based on the textString
UIFont *font = [UIFont systemFontOfSize:14];
CGSize size = [chatText sizeWithFont:font constrainedToSize:CGSizeMake(150.0f, 1000.0f) lineBreakMode:NSLineBreakByCharWrapping];
return size.height+20.0; //or whatever padding value you need
【讨论】:
谢谢。我做到了,但图像彼此重叠 [屏幕截图] (postimg.org/image/70gu53sp7) @User 更新了我的答案。您需要计算每一行的高度。请相应调整高度计算。 这里有问题:CGRectGetMaxY(cell.textString.frame)+10.0 of line self.bubbleImage.frame = CGRectMake(0,22,250,CGRectGetMaxY(cell.textString.frame)+10.0);因为我将单个单元格的 2/3 图像作为screenshot @User 你如何计算每一行的高度? 如你所说。但我将填充值增加到 100 而不是 20。以上是关于将imageview添加为uitableviewcell的子视图时如何使imageview可拉伸的主要内容,如果未能解决你的问题,请参考以下文章
JavaFX 将 ImageView 裁剪为 AnchorPane 中的椭圆