我使用的是自定义UITableViewCell,它可以显示一些标签,按钮和图像视图。单元格中有一个标签,其文本为NSString
对象,字符串的长度可以是可变的。因此,我无法在UITableView
的{{1}}方法中为单元格设置恒定的高度。单元格的高度取决于标签的高度,可以使用heightForCellAtIndex
的{{1}}方法确定。我尝试过使用它,但看起来我在某个地方出错了。如何解决?
以下是用于初始化单元格的代码。
NSString
这是高度和宽度出错的标签:
sizeWithFont
答案 0 :(得分:492)
您的UITableViewDelegate
应该实施tableView:heightForRowAtIndexPath:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [indexPath row] * 20;
}
您可能希望使用NSString
的{{1}}方法来计算行高,而不是仅仅对indexPath执行一些愚蠢的数学运算:)
答案 1 :(得分:131)
如果所有行的高度相同,只需设置UITableView的rowHeight
属性,而不是实现heightForRowAtIndexPath
。 Apple Docs:
使用tableView:heightForRowAtIndexPath:而不是rowHeight会对性能产生影响。每次显示表视图时,它都会在每个行的委托上调用tableView:heightForRowAtIndexPath:这会导致表视图具有大量行(大约1000或更多)的显着性能问题。
答案 2 :(得分:24)
在自定义UITableViewCell控制器中添加此
-(void)layoutSubviews {
CGRect newCellSubViewsFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
CGRect newCellViewFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
self.contentView.frame = self.contentView.bounds = self.backgroundView.frame = self.accessoryView.frame = newCellSubViewsFrame;
self.frame = newCellViewFrame;
[super layoutSubviews];
}
在UITableView -controller中添加此
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [indexPath row] * 1.5; // your dynamic height...
}
答案 3 :(得分:17)
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 300.0f
#define CELL_CONTENT_MARGIN 10.0f
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
/// Here you can set also height according to your section and row
if(indexPath.section==0 && indexPath.row==0)
{
text=@"pass here your dynamic data";
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);
}
else
{
return 44;
}
}
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
UILabel *label = nil;
cell = [tv dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"];
}
********Here you can set also height according to your section and row*********
if(indexPath.section==0 && indexPath.row==0)
{
label = [[UILabel alloc] initWithFrame:CGRectZero];
[label setLineBreakMode:UILineBreakModeWordWrap];
[label setMinimumFontSize:FONT_SIZE];
[label setNumberOfLines:0];
label.backgroundColor=[UIColor clearColor];
[label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
[label setTag:1];
// NSString *text1 =[NSString stringWithFormat:@"%@",text];
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];
label.text=[NSString stringWithFormat:@"%@",text];
[label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
[cell.contentView addSubview:label];
}
return cell;
}
答案 4 :(得分:8)
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
CGSize constraintSize = {245.0, 20000}
CGSize neededSize = [ yourText sizeWithFont:[UIfont systemFontOfSize:14.0f] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeCharacterWrap]
if ( neededSize.height <= 18)
return 45
else return neededSize.height + 45
//18 is the size of your text with the requested font (systemFontOfSize 14). if you change fonts you have a different number to use
// 45 is what is required to have a nice cell as the neededSize.height is the "text"'s height only
//not the cell.
}
答案 5 :(得分:7)
我看到了很多解决方案,但都是错误的或不完整的。 您可以在viewDidLoad和autolayout中解决5行的所有问题。 这对于客观的C:
_tableView.delegate = self;
_tableView.dataSource = self;
self.tableView.estimatedRowHeight = 80;//the estimatedRowHeight but if is more this autoincremented with autolayout
self.tableView.rowHeight = UITableViewAutomaticDimension;
[self.tableView setNeedsLayout];
[self.tableView layoutIfNeeded];
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) ;
对于swift 2.0:
self.tableView.estimatedRowHeight = 80
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.setNeedsLayout()
self.tableView.layoutIfNeeded()
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0)
现在使用xib创建您的单元格或在Storyboard中创建tableview 有了这个你不需要实现任何更多或覆盖。 (不要忘记数字os行0)和底部标签(约束)降级“内容拥抱优先级 - 垂直到250”
您可以在下一个网址中下载代码: https://github.com/jposes22/exampleTableCellCustomHeight
答案 6 :(得分:5)
感谢这个主题的所有帖子,有一些非常有用的方法来调整UITableViewCell的rowHeight。
以下是其他所有人在构建iPhone和iPad时真正有用的概念汇编。您还可以访问不同的部分,并根据不同的视图大小进行调整。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
int cellHeight = 0;
if ([indexPath section] == 0)
{
cellHeight = 16;
settingsTable.rowHeight = cellHeight;
}
else if ([indexPath section] == 1)
{
cellHeight = 20;
settingsTable.rowHeight = cellHeight;
}
return cellHeight;
}
else
{
int cellHeight = 0;
if ([indexPath section] == 0)
{
cellHeight = 24;
settingsTable.rowHeight = cellHeight;
}
else if ([indexPath section] == 1)
{
cellHeight = 40;
settingsTable.rowHeight = cellHeight;
}
return cellHeight;
}
return 0;
}
答案 7 :(得分:4)
设置行高的自动尺寸&amp;估计行高,确保执行以下步骤,自动尺寸对单元格/行高度布局有效。
(gdb) backtrace
#0 0x00007ffff4c49428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
#1 0x00007ffff4c4b02a in __GI_abort () at abort.c:89
#2 0x00007ffff4c41bd7 in __assert_fail_base (fmt=<optimized out>,
assertion=assertion@entry=0x7fffd779f940 "entry.expiry > omnetpp::simTime() && entry.expiry < omnetpp::simTime() + 2.0",
file=file@entry=0x7fffd779f8f0 "/home/wiconlab/Car2x/artery-master/src/artery/application/LocalDynamicMap.cc", line=line@entry=24,
function=function@entry=0x7fffd779f9a0 <artery::LocalDynamicMap::updateAwareness(CaObject const&)::__PRETTY_FUNCTION__> "void artery::LocalDynamicMap::updateAwareness(const CaObject&)")
at assert.c:92
#3 0x00007ffff4c41c82 in __GI___assert_fail (
assertion=0x7fffd779f940 "entry.expiry > omnetpp::simTime() && entry.expiry < omnetpp::simTime() + 2.0",
file=0x7fffd779f8f0 "/home/wiconlab/Car2x/artery-master/src/artery/application/LocalDynamicMap.cc", line=24,
function=0x7fffd779f9a0 <artery::LocalDynamicMap::updateAwareness(CaObject const&)::__PRETTY_FUNCTION__> "void artery::LocalDynamicMap::updateAwareness(const CaObject&)") at assert.c:101
#4 0x00007fffd7703ab8 in artery::LocalDynamicMap::updateAwareness (this=0x1d62c7a8, obj=...)
at /home/wiconlab/Car2x/artery-master/src/artery/application/LocalDynamicMap.cc:24
Python Exception <class 'TypeError'> expected string or bytes-like object:
#5 0x00007fffd76f31f8 in CaService::indicate (this=0x6625550, ind=..., packet=)
at /home/wiconlab/Car2x/artery-master/src/artery/application/CaService.cc:89
#6 0x00007fffd4202d91 in vanetza::btp::PortDispatcher::indicate(vanetza::geonet::DataIndication const&, std::unique_ptr<boost::variant<vanetza::ChunkPacket, vanetza::CohesivePacket>, std::default_delete<boost::variant<vanetza::ChunkPacket, vanetza::CohesivePacket> > >) ()
from /home/wiconlab/Car2x/artery-master/extern/vanetza/build/lib/libvanetza_btp.so
#7 0x00007fffd3d3609f in vanetza::geonet::Router::pass_up(vanetza::geonet::DataIndication&, std::unique_ptr<boost::variant<vanetza::ChunkPacket, vanetza::CohesivePacket>, std::default_delete<boost::variant<vanetza::ChunkPacket, vanetza::CohesivePacket> > >) ()
from /home/wiconlab/Car2x/artery-master/extern/vanetza/build/lib/libvanetza_geonet.so
#8 0x00007fffd3d362f9 in vanetza::geonet::Router::process_extended(vanetza::geonet::ExtendedPduConstRefs<vanetza::geonet::ShbHeader> const&, std::unique_ptr<boost::variant<vanetza::ChunkPacket, vanetza::CohesivePacket>, std::default_delete<boost::variant<vanetza::ChunkPacket, vanetza::CohesivePacket> > >) () from /home/wiconlab/Car2x/artery-master/extern/vanetza/build/lib/libvanetza_geonet.so
#9 0x00007fffd3d378f7 in vanetza::geonet::Router::indicate_extended(vanetza::geonet::IndicationContext&, vanetza::geonet::CommonHeader const&) ()
from /home/wiconlab/Car2x/artery-master/extern/vanetza/build/lib/libvanetza_geonet.so
#10 0x00007fffd3d37b37 in vanetza::geonet::Router::indicate_common(vanetza::geonet::IndicationContext&, vanetza::geonet::BasicHeader const&) ()
from /home/wiconlab/Car2x/artery-master/extern/vanetza/build/lib/libvanetza_geonet.so
#11 0x00007fffd3d39623 in vanetza::geonet::Router::indicate_secured(vanetza::geonet::IndicationContext&, vanetza::geonet::BasicHeader const&) ()
from /home/wiconlab/Car2x/artery-master/extern/vanetza/build/lib/libvanetza_geonet.so
#12 0x00007fffd3d39998 in vanetza::geonet::Router::indicate(std::unique_ptr<boost::variant<vanetza::ChunkPacket, vanetza::CohesivePacket>, std::default_delete<boost::variant<vanetza::ChunkPacket, vanetza::CohesivePacket> > >, vanetza::MacAddress const&, vanetza::MacAddress const&) ()
from /home/wiconlab/Car2x/artery-master/extern/vanetza/build/lib/libvanetza_geonet.so
#13 0x00007fffd7707bc5 in artery::Middleware::handleLowerMsg (this=0x1d62c650, msg=0x2ea0df0)
at /home/wiconlab/Car2x/artery-master/src/artery/application/Middleware.cc:303
#14 0x00007fffd7707a45 in artery::Middleware::handleMessage (this=0x1d62c650, msg=0x2ea0df0)
at /home/wiconlab/Car2x/artery-master/src/artery/application/Middleware.cc:283
#15 0x00007ffff682e477 in omnetpp::cSimulation::doMessageEvent (this=0x7b6b10, msg=0x2ea0df0,
module=0x1d62c650) at csimulation.cc:669
#16 0x00007ffff682e152 in omnetpp::cSimulation::executeEvent (this=0x7b6b10, event=0x2ea0df0)
at csimulation.cc:611
#17 0x00007ffff74e9075 in omnetpp::qtenv::Qtenv::doRunSimulationExpress (this=0x7b8a50)
at qtenv.cc:968
#18 0x00007ffff74e8526 in omnetpp::qtenv::Qtenv::runSimulation (this=0x7b8a50,
mode=omnetpp::qtenv::RUNMODE_EXPRESS, until_time=..., until_eventnum=0, until_msg=0x0,
until_module=0x0, stopOnMsgCancel=true) at qtenv.cc:731
#19 0x00007ffff746ed8d in omnetpp::qtenv::MainWindow::runSimulation (this=0x252f060,
runMode=omnetpp::qtenv::RUNMODE_EXPRESS) at mainwindow.cc:507
#20 0x00007ffff74a80df in omnetpp::qtenv::MainWindow::on_actionExpressRun_triggered (this=0x252f060)
at mainwindow.h:98
#21 0x00007ffff74a7a3f in omnetpp::qtenv::MainWindow::qt_static_metacall (_o=0x252f060,
_c=QMetaObject::InvokeMetaMethod, _id=5, _a=0x7fffffffc740) at moc_mainwindow.cpp:273
#22 0x00007ffff74a7f7c in omnetpp::qtenv::MainWindow::qt_metacall (this=0x252f060,
_c=QMetaObject::InvokeMetaMethod, _id=5, _a=0x7fffffffc740) at moc_mainwindow.cpp:363
#23 0x00007ffff44aaee0 in QMetaObject::activate(QObject*, int, int, void**) ()
from /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
#24 0x00007ffff3cba412 in QAction::triggered(bool) ()
from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#25 0x00007ffff3cbc898 in QAction::activate(QAction::ActionEvent) ()
from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#26 0x00007ffff3dc25a0 in ?? () from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#27 0x00007ffff3dc26d4 in QAbstractButton::mouseReleaseEvent(QMouseEvent*) ()
from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#28 0x00007ffff3e8726a in QToolButton::mouseReleaseEvent(QMouseEvent*) ()
from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#29 0x00007ffff3d06fc8 in QWidget::event(QEvent*) ()
from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#30 0x00007ffff3e87349 in QToolButton::event(QEvent*) ()
from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#31 0x00007ffff3cc405c in QApplicationPrivate::notify_helper(QObject*, QEvent*) ()
from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#32 0x00007ffff3cc9c19 in QApplication::notify(QObject*, QEvent*) ()
from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#33 0x00007ffff447c38b in QCoreApplication::notifyInternal(QObject*, QEvent*) ()
from /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
#34 0x00007ffff3cc8b32 in QApplicationPrivate::sendMouseEvent(QWidget*, QMouseEvent*, QWidget*, QWidget*, QWidget**, QPointer<QWidget>&, bool) () from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#35 0x00007ffff3d215bb in ?? () from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#36 0x00007ffff3d23b7b in ?? () from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#37 0x00007ffff3cc405c in QApplicationPrivate::notify_helper(QObject*, QEvent*) ()
from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#38 0x00007ffff3cc9516 in QApplication::notify(QObject*, QEvent*) ()
from /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5
#39 0x00007ffff447c38b in QCoreApplication::notifyInternal(QObject*, QEvent*) ()
from /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
#40 0x00007ffff47be4e1 in QGuiApplicationPrivate::processMouseEvent(QWindowSystemInterfacePrivate::MouseEvent*) () from /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5
#41 0x00007ffff47c01a5 in QGuiApplicationPrivate::processWindowSystemEvent(QWindowSystemInterfacePrivate::WindowSystemEvent*) () from /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5
#42 0x00007ffff47a3f08 in QWindowSystemInterface::sendWindowSystemEvents(QFlags<QEventLoop::ProcessEventsFlag>) () from /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5
#43 0x00007fffd1b74200 in ?? () from /usr/lib/x86_64-linux-gnu/libQt5XcbQpa.so.5
#44 0x00007fffefd69197 in g_main_context_dispatch () from /lib/x86_64-linux-gnu/libglib-2.0.so.0
#45 0x00007fffefd693f0 in ?? () from /lib/x86_64-linux-gnu/libglib-2.0.so.0
#46 0x00007fffefd6949c in g_main_context_iteration () from /lib/x86_64-linux-gnu/libglib-2.0.so.0
#47 0x00007ffff44d27cf in QEventDispatcherGlib::processEvents(QFlags<QEventLoop::ProcessEventsFlag>)
() from /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
#48 0x00007ffff4479b4a in QEventLoop::exec(QFlags<QEventLoop::ProcessEventsFlag>) ()
from /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
#49 0x00007ffff4481bec in QCoreApplication::exec() () from /usr/lib/x86_64-linux-gnu/libQt5Core.so.5
#50 0x00007ffff74e7ce6 in omnetpp::qtenv::Qtenv::doRun (this=0x7b8a50) at qtenv.cc:628
#51 0x00007ffff78f8ba0 in omnetpp::envir::EnvirBase::run (this=0x7b8a60) at envirbase.cc:748
#52 0x00007ffff78f5ed8 in omnetpp::envir::EnvirBase::run (this=0x7b8a60, argc=6,
argv=0x7fffffffda98, configobject=0x7bc750) at envirbase.cc:337
#53 0x00007ffff78ee1f9 in omnetpp::envir::setupUserInterface (argc=6, argv=0x7fffffffda98)
at startup.cc:259
#54 0x00007ffff78ef930 in omnetpp::envir::evMain (argc=6, argv=0x7fffffffda98) at evmain.cc:33
#55 0x0000000000402340 in main (argc=6, argv=0x7fffffffda98) at opp_run.cc:321
分配给rowHeight&amp; estimatedRowHeight UITableViewAutomaticDimension
并向其返回值heightForRowAt
)-
目标C:
UITableViewAutomaticDimension
<强>夫特:强>
// in ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
@property IBOutlet UITableView * table;
@end
// in ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.table.dataSource = self;
self.table.delegate = self;
self.table.rowHeight = UITableViewAutomaticDimension;
self.table.estimatedRowHeight = UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
用于UITableviewCell中的标签实例
注意:如果您有多个动态长度的标签(UIElements),应根据其内容大小进行调整:调整您的标签'内容拥抱和压缩阻力优先级'想要以更高的优先级扩展/压缩。
在这个例子中,我设置了低拥抱和高压缩阻力优先级,这导致为第二(黄色)标签的内容设置更多优先级/重要性。
答案 8 :(得分:3)
要使动态单元格高度随着Label文本的增加而增加,首先需要计算高度,文本将在-heightForRowAtIndexPath
委托方法中使用,并返回其他标签的增加高度,图像(最大值)文本高度+其他静态组件的高度)并在单元格创建中使用相同的高度。
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 300.0f
#define CELL_CONTENT_MARGIN 10.0f
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
if (indexPath.row == 2) { // the cell you want to be dynamic
NSString *text = dynamic text for your label;
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);
}
else {
return 44; // return normal cell height
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UILabel *label;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] ;
}
label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 280, 34)];
[label setNumberOfLines:2];
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
label.adjustsFontSizeToFitWidth = NO;
[[cell contentView] addSubview:label];
NSString *text = dynamic text fro your label;
[label setText:text];
if (indexPath.row == 2) {// the cell which needs to be dynamic
[label setNumberOfLines:0];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
[label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
}
return cell;
}