[ios]tableView内部cell因内容大小变换 而变化 sizeWithFont:constrainedToSize: lineBreakMode:

[NSString*对象 sizeWithFont:constrainedToSize:]

这个方法用于获取 以传入模式下的 字符串像素大小。

 

这玩意今天坑了我很久。表示 各种陷阱。

如果你是从android转过来的 请看看下面。

首先 如果使用ios6的autolayout你会在最后发现你被坑了。

然后ios 的tablecell不会随着你的内容变化的缩小放大。

lableView也不会。

更蛋疼的是lableView不会换行--》也就是说你需要自己处理换行。今天用了个递归去+“/n”

自己换行就算了- -,还需要自己设置行数。否则显示不出来的亲。

 

【改:如果你把行数默认成0的话 他会自适应行数 也就是说 你内容有多少行他就多少行 但是frame还是要自己设置】

计算行数

【计算移动距离不需要通过行数。】

str为输入内容  move 为算出 当前frame相对于单行是移动了多少。[用于给其他受影响的view修改orgain.x]

 

    CGSize size=[str sizeWithFont:[UIFont systemFontOfSize:17.0]constrainedToSize:CGSizeMake(210.0f,1000.0f ) lineBreakMode:NSLineBreakByWordWrapping];

 

    //str字符串以sizeWithFont 的字体模式 单词切割模式 传入指定的大小的size[宽度超过210就换行] 所需要的实际高度和宽度。

    //【传入的size 为限制值,高度和宽度最大只能为传入宽度大小】

        CGSize size2=[@"1" sizeWithFont:[UIFont systemFontOfSize:17.0]constrainedToSize:CGSizeMake(210.0f,1000.0f ) lineBreakMode:NSLineBreakByWordWrapping];

int move=size.height-size2.height

 

总结一下:

1.你需要知道你的内容的行数。

2.你需要对你内容 进行换行处理并且设置行数。

【在stroyboard里面设置lable行数为0,既可自动换行】

 

3.你需要根据你内容的行数修改你的布局。包括自己的frame.size.height,被影响的frame.origen.y[计算出 位移(当前size-@""的size),然后给+被影响的]。

4.你还要修改cell的高度。

5.确定不要使用autoLayout。

 

 

 

 

下面是demo 这个demo里面很多老东西 可以别看- -

Oc代码   收藏代码
  1. <pre class="oc" name="code">//  
  2. //  tableViewVC.m  
  3. //  swearWorldDemo  
  4. //  
  5. //  Created by liu poolo on 12-10-17.  
  6. //  Copyright (c) 2012年 liu poolo. All rights reserved.  
  7. //  
  8.   
  9. #import "tableViewVC.h"  
  10. #import "MyXMLParser.h"  
  11. #import "SwearVO.h"  
  12. #import "CountryVO.h"  
  13. #import <Social/Social.h>  
  14. #import <QuartzCore/QuartzCore.h>  
  15. #import "ButtonCell.h"  
  16.   
  17. @interface tableViewVC ()  
  18. @property NSMutableArray *array;  
  19.   
  20. @property NSString *pathSwear;  
  21. @property (nonatomic)  NSString *pathCountry;  
  22. @property NSInteger currentSection;  
  23. @property NSString *text;  
  24. @property UIImage *image;  
  25. @property NSArray *fireImages;  
  26.   
  27.   
  28. @end  
  29.   
  30. @implementation tableViewVC  
  31.   
  32. @synthesize array=_array;  
  33. @synthesize pathCountry=_pathCountry;  
  34. @synthesize pathSwear=_pathSwear;  
  35. @synthesize swearDy=_swearDy;  
  36. @synthesize countryDy=_countryDy;  
  37. @synthesize text=_text;  
  38. @synthesize image=_image;  
  39. @synthesize fireImages;  
  40.   
  41. - (void)setSwearDy:(NSArray *)swearDy{  
  42.     if(_swearDy!=swearDy){  
  43.         _swearDy=swearDy;  
  44.         [self.tableView reloadData];  
  45.         NSLog(@"setSwearDy");  
  46.     }  
  47. }  
  48.   
  49.   
  50. - (id)initWithStyle:(UITableViewStyle)style  
  51. {  
  52.     self = [super initWithStyle:style];  
  53.     if (self) {  
  54.         // Custom initialization  
  55.     }  
  56.     return self;  
  57. }  
  58.   
  59. - (void)viewDidLoad  
  60. {  
  61.     [super viewDidLoad];  
  62.       
  63.     //    self.pathSwear=[[NSBundle mainBundle] pathForResource:@"swearList" ofType:@"plist"];  
  64.     //    self.swearDy=[NSArray arrayWithContentsOfFile:self.pathSwear];  
  65.     //    self.pathCountry=[[NSBundle mainBundle] pathForResource:@"countryList" ofType:@"plist"];  
  66.     //    self.countryDy=[NSArray arrayWithContentsOfFile:self.pathCountry];  
  67.     self.currentSection=-1;  
  68.     NSLog(@"viewDidLoad");  
  69.       
  70.     //设置table的一些参数  
  71.     self.tableView.backgroundView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"background.jpg"]];  
  72.     self.tableView.sectionIndexColor=[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1];  
  73.     self.tableView.sectionIndexTrackingBackgroundColor=[UIColor colorWithRed:0.50196081399917603 green:0.25098040699958801 blue:0.0 alpha:0.6];  
  74.       
  75.     //加载fireImage;  
  76.     self.fireImages=@[[UIImage imageNamed:@"fire1.png"],[UIImage imageNamed:@"fire2.png"],[UIImage imageNamed:@"fire3.png"],[UIImage imageNamed:@"fire4.png"],[UIImage imageNamed:@"fire5.png"],[UIImage imageNamed:@"fire6.png"]];  
  77. }  
  78. -(void)viewWillAppear:(BOOL)animated{  
  79.     NSLog(@"viewWillAppear");  
  80. }  
  81.   
  82. - (void)didReceiveMemoryWarning  
  83. {  
  84.     [super didReceiveMemoryWarning];  
  85.     // Dispose of any resources that can be recreated.  
  86. }  
  87.   
  88. #pragma mark - Table view data source  
  89.   
  90. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView  
  91. {  
  92.       
  93.     return [self.countryDy count];  
  94. }  
  95.   
  96. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
  97. {  
  98.       
  99.     NSInteger countryID=[self getCountryIdBySession:section];  
  100.     return  [[self getArrayByCountryId:countryID] count];  
  101. }  
  102.   
  103. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  104. {  
  105.     static NSString *CellIdentifier = @"swearInfo";  
  106.     ButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];  
  107.     if(cell==nil){  
  108.         cell=[[ButtonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];  
  109.     }  
  110.       
  111.     if(self.currentSection!=indexPath.section){  
  112.         //进入新的section了  
  113.         NSInteger countryID=[self getCountryIdBySession:indexPath.section];  
  114.         self.array=[[self getArrayByCountryId:countryID] mutableCopy];  
  115.     }  
  116.     cell= [self CellSetedByRow:indexPath.row withArray:self.array andCell:cell];  
  117.     //  修改 右边 导航栏背景色  残疾法  
  118.     //    for(UIView *view in [tableView subviews])  
  119.     //    {  
  120.     //  
  121.     //        if([[[view class] description] isEqualToString:@"UITableViewIndex"])  
  122.     //        {  
  123.     //  
  124.       
  125.                 if(indexPath.row%2){  
  126.                 [view setBackgroundColor:[UIColor yellowColor]];  
  127.                 }else{  
  128.                 [view setBackgroundColor:[UIColor blueColor]];  
  129.                 }  
  130.       
  131.     //            [view setFont:[UIFont systemFontOfSize:14]];  
  132.     //        }  
  133.     //    }  
  134.     return cell ;  
  135. }  
  136.   
  137. - (NSArray *)getArrayByCountryId:(NSInteger) countryid{  
  138.     //根据国家ID获取对应粗口数组  
  139.     NSMutableArray * tempArray=[[NSMutableArray alloc]init];  
  140.     for(CountryVO *a  in self.swearDy){  
  141.         if([a.countryId integerValue]==countryid){  
  142.             [tempArray addObject:a];  
  143.               
  144.         }  
  145.     }  
  146.     return tempArray;  
  147. }  
  148.   
  149. - (NSInteger)getCountryIdBySession:(NSInteger) section{  
  150.     //通过session获得国家id  
  151.     NSInteger result=0;  
  152.     CountryVO * tempD=(CountryVO *)[self.countryDy objectAtIndex:section];  
  153.     result =[tempD.countryId integerValue];  
  154.     return  result;  
  155.       
  156. }  
  157.   
  158. - (NSString *)CountryNameBySession:(NSInteger) section{  
  159.     //通过session获得国家名  
  160.     NSString *result=0;  
  161.     CountryVO *tempD=(CountryVO *)[self.countryDy objectAtIndex:section];  
  162.     result = tempD.countryName;  
  163.     return  result;  
  164. }  
  165. //  
  166. //-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{  
  167. //  
  168. //  
  169. //}  
  170.   
  171. #define BASEHEIGHT 76 //cell初始状态高度  
  172. #define PERHEIGHT 20 //每次行增加距离  
  173. #define DEFAULT 27 //初始name 高度  
  174. #define rowSize 22 //每行字节数  
  175. #define DEFAULTDSCRIBE 24  //出状态DSCRIBE 高度  
  176.   
  177. - (ButtonCell *)CellSetedByRow:(NSInteger)row withArray:(NSArray *)a andCell:(ButtonCell *)cell{  
  178.     //根据行号,对应的数组,和CELL设置CELL。  
  179.     SwearVO * swearVO= (SwearVO *)[a objectAtIndex:row];  
  180.     //        UILabel * labCountry=(UILabel *)[cell viewWithTag:-1];  
  181.     //        UILabel * labName=(UILabel *)[cell viewWithTag:-2];  
  182.     //        UILabel * labLevel=(UILabel *)[cell viewWithTag:-3];  
  183.             UILabel * labImagePath=(UILabel *)[cell viewWithTag:-4];  
  184.     //        UILabel * labdescribe=(UILabel *)[cell viewWithTag:-5];  
  185.     //        UIButton *bt=(UIButton *)[cell viewWithTag:-6];  
  186.       
  187.     //    ((UILabel *)[cell viewWithTag:10]).text=@"这里是Cellview";  
  188.     //      简单说明下想对cell直接丢text[虽然我估计你不会这么操作,而且这么操作会让子VIEW不显示]  
  189.     //      是无法使用cell.text的  
  190.     //      而是使用cell viewWithTag:x  
  191.     //      这里很有趣cell能通过自己的viewWithTag 来获取自己顶层的view[此view无法循环viweWithTag]。然后进行操作。  
  192.       
  193.     //    UITableViewCell * b=((UITableViewCell *)[cell viewWithTag:10]);  
  194.     //    ((UILabel *)[b viewWithTag:1]).text=@"so funy";  
  195.       
  196.     //赋值  
  197.     cell.idlb.text=swearVO.swearId;  
  198.     cell.describe.text=swearVO.swearIntroduce;  
  199.     cell.button.tag=[swearVO.swearId integerValue];  
  200.     if([self.fireImages objectAtIndex:[swearVO.fireLever integerValue]-1]){  
  201.         cell.fire.image=[self.fireImages objectAtIndex:[swearVO.fireLever integerValue]-1];  
  202.     }  
  203.       
  204.     //计算cell变化 start  
  205.     int line;  
  206.     if(swearVO.swearName.length%rowSize){  
  207.         line =(swearVO.swearName.length/rowSize)+1;  
  208.     }else{  
  209.         line=(swearVO.swearName.length/rowSize);  
  210.     }  
  211.       
  212.       
  213.   
  214.     NSString *str=swearVO.swearName ;  
  215.   
  216.       
  217.     CGSize size=[str sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:CGSizeMake(210.0f,1000.0f ) lineBreakMode:NSLineBreakByWordWrapping];  
  218.         CGSize size2=[@"1" sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:CGSizeMake(210.0f,1000.0f ) lineBreakMode:NSLineBreakByWordWrapping];  
  219.       
  220.     //name frame修改  
  221.     CGRect rect=cell.name.frame;  
  222.     rect.size.height=size.height;  
  223.     int move=size.height-size2.height;  
  224.     cell.name.frame=rect;  
  225.       
  226.     //name内容增加"\n"换行符 那个方法用了递归  
  227.   
  228.     cell.name.text=str;  
  229.   
  230.       
  231.     //修改Dscribe位置  
  232.     CGRect rectDscribe;  
  233.     rectDscribe=cell.describe.frame;  
  234. //    NSLog(@"%f!!!!!!!!",rectDscribe.origin.y);  
  235.     rectDscribe.origin.y=DEFAULTDSCRIBE+move;  
  236.     cell.describe.frame=rectDscribe;  
  237.     //    cell.name.bounds=rectBound;  
  238.       
  239.       
  240.   
  241. //    NSLog(@"%d|%f|%f",[cell.name numberOfLines], cell.name.bounds.size.height, cell.name.frame.size.height);  
  242.       
  243.       
  244.       
  245.       
  246.     //   labCountry.text=swearVO.countryId;  
  247.     //    labName.text=swearVO.swearName;  
  248.     //   labLevel.text=swearVO.fireLever;  
  249.     //    labdescribe.text=    cell.describe.text=swearVO.swearIntroduce;  
  250.     //    bt.tag=[swearVO.swearId integerValue];  
  251.       
  252.     //    if(row%2){  
  253.     //        cell.contentView.backgroundColor=[UIColor yellowColor];  
  254.     //    }else{  
  255.     //        cell.contentView.backgroundColor=[UIColor yellowColor];  
  256.     //    }  
  257.     return cell;  
  258. }  
  259.   
  260. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{  
  261.     return [self CountryNameBySession:section];  
  262. }  
  263.   
  264.   
  265.   
  266. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{  
  267.     CGFloat height;  
  268.     NSInteger countryID=[self getCountryIdBySession:indexPath.section];  
  269.     NSArray *array=[[self getArrayByCountryId:countryID] mutableCopy];  
  270.     SwearVO *swearVO=(SwearVO *)[array objectAtIndex:indexPath.row];  
  271.     int line=(swearVO.swearName.length/(rowSize+1))+1;  
  272.     height=BASEHEIGHT+(line-1)*PERHEIGHT;  
  273.     return height;  
  274.       
  275. }  
  276.   
  277. /*  
  278.  // Override to support conditional editing of the table view.  
  279.  - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath  
  280.  {  
  281.  // Return NO if you do not want the specified item to be editable.  
  282.  return YES;  
  283.  }  
  284.  */  
  285.   
  286. /*  
  287.  // Override to support editing the table view.  
  288.  - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath  
  289.  {  
  290.  if (editingStyle == UITableViewCellEditingStyleDelete) {  
  291.  // Delete the row from the data source  
  292.  [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];  
  293.  }  
  294.  else if (editingStyle == UITableViewCellEditingStyleInsert) {  
  295.  // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view  
  296.  }  
  297.  }  
  298.  */  
  299.   
  300. /*  
  301.  // Override to support rearranging the table view.  
  302.  - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath  
  303.  {  
  304.  }  
  305.  */  
  306.   
  307. /*  
  308.  // Override to support conditional rearranging of the table view.  
  309.  - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath  
  310.  {  
  311.  // Return NO if you do not want the item to be re-orderable.  
  312.  return YES;  
  313.  }  
  314.  */  
  315.   
  316. #pragma mark - Table view delegate  
  317.   
  318. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  
  319. {  
  320.     [self srceenShot];  
  321.     NSInteger countryID=[self getCountryIdBySession:indexPath.section];  
  322.     self.array=[[self getArrayByCountryId:countryID] mutableCopy];  
  323.     SwearVO *swearVO=(SwearVO *)[self.array objectAtIndex:indexPath.row];  
  324.     [self shareWithText:swearVO.swearName];  
  325.       
  326.       
  327. }  
  328.   
  329. - (void)shareWithText:(NSString *)text{  
  330.     NSArray *activityItems;  
  331.     self.text=text;  
  332.     if(self.image){  
  333.         activityItems=@[self.text,self.image];  
  334.     }else{  
  335.         activityItems=@[self.text];  
  336.     }  
  337.     UIActivityViewController *avc=[[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];  
  338.     [self presentViewController:avc animated:YES completion:nil];  
  339.       
  340.       
  341. }  
  342.   
  343. - (void)srceenShot{  
  344.     //    UIGraphicsPushContext(UIGraphicsGetCurrentContext());  
  345.     UIGraphicsPushContext(UIGraphicsGetCurrentContext());  
  346.     UIGraphicsBeginImageContext(self.view.bounds.size);  
  347.     [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];  
  348.       
  349.     self.image=UIGraphicsGetImageFromCurrentImageContext();  
  350.     UIGraphicsEndImageContext();  
  351.     UIGraphicsPopContext();  
  352.     //    UIGraphicsPopContext();  
  353.       
  354. }  
  355.   
  356.   
  357. - (IBAction)btVideoPressed:(UIButton *)sender {  
  358.     //    UITableViewCell *cell=(UITableViewCell *)sender.superview;  
  359.     NSLog(@"%d",sender.tag);  
  360. }  
  361.   
  362. -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{  
  363.     //用于设置sectionIndexTitle  
  364.     //返回要为一个内容为NSString 的NSArray 里面存放section title;  
  365.     //默认情况下 section Title根据顺序对应 section 【如果不写tableView: sectionForSectionIndexTitle: atIndex:的话】  
  366.     NSMutableArray* a=[NSMutableArray array];  
  367.     for(CountryVO *c in self.countryDy){  
  368.         [a addObject: [c.countryName substringToIndex:1]];  
  369.     }  
  370.       
  371.       
  372.     //    self.tableView.sec  
  373.     //    self.tableView.sectionIndexTrackingBackgroundColor=[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];  
  374.       
  375.     //    return b=@[@"1",@"2"];  
  376.     return a;  
  377. }  
  378.   
  379.   
  380. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{  
  381.     //传入 section title 和index 返回其应该对应的session序号。  
  382.     //一般不需要写 默认section index 顺序与section对应。除非 你的section index数量或者序列与section不同才用修改  
  383.     return index;  
  384. }  
  385.   
  386. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{  
  387.       
  388.     UIImageView *result=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"title_bg.png"]];  
  389.     UILabel *content=[[UILabel alloc]initWithFrame:CGRectZero];  
  390.     content.frame = CGRectMake(10.00.0300.018.0);  
  391.     content.font=[UIFont systemFontOfSize:15];  
  392.     content.backgroundColor=[UIColor clearColor];  
  393.     content.textColor=[UIColor whiteColor];  
  394.       
  395.     content.text=((CountryVO *)[self.countryDy objectAtIndex:section]).countryName;  
  396.     [result addSubview:content];  
  397.     return result;  
  398.       
  399. }  
  400.   
  401. //根据传入的string增补 "\n"  
  402. //注:【在stroyboard里面设置lable行数为0,既可自动换行】  
  403. //-(NSString *)stringWillNByString:(NSString *)str line:(NSInteger)lineNum{  
  404. //    NSString *firstStr;  
  405. //    NSString *secondStr;  
  406. //    if(str.length>rowSize){  
  407. //        firstStr=[str substringToIndex:rowSize];  
  408. //        firstStr=[firstStr stringByAppendingString:@"\n"];  
  409. //        secondStr=[str substringFromIndex:rowSize];  
  410. //        [self stringWillNByString:secondStr line:lineNum-1];  
  411. //        return [NSString stringWithFormat:@"%@%@",firstStr,secondStr];  
  412. //    }else{  
  413. //        secondStr=str;  
  414. //        return secondStr;  
  415. //    }  
  416. //      
  417. //      
  418. //}  
  419.   
  420. @end  
  421. </pre>  
  422.    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值