`
119568242
  • 浏览: 420793 次
  • 性别: Icon_minigender_1
  • 来自: 深圳/湛江
社区版块
存档分类
最新评论

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

    博客分类:
  • ios
 
阅读更多

 

 [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里面很多老东西 可以别看- -

//
//  tableViewVC.m
//  swearWorldDemo
//
//  Created by liu poolo on 12-10-17.
//  Copyright (c) 2012年 liu poolo. All rights reserved.
//

#import "tableViewVC.h"
#import "MyXMLParser.h"
#import "SwearVO.h"
#import "CountryVO.h"
#import <Social/Social.h>
#import <QuartzCore/QuartzCore.h>
#import "ButtonCell.h"

@interface tableViewVC ()
@property NSMutableArray *array;

@property NSString *pathSwear;
@property (nonatomic)  NSString *pathCountry;
@property NSInteger currentSection;
@property NSString *text;
@property UIImage *image;
@property NSArray *fireImages;


@end

@implementation tableViewVC

@synthesize array=_array;
@synthesize pathCountry=_pathCountry;
@synthesize pathSwear=_pathSwear;
@synthesize swearDy=_swearDy;
@synthesize countryDy=_countryDy;
@synthesize text=_text;
@synthesize image=_image;
@synthesize fireImages;

- (void)setSwearDy:(NSArray *)swearDy{
    if(_swearDy!=swearDy){
        _swearDy=swearDy;
        [self.tableView reloadData];
        NSLog(@"setSwearDy");
    }
}


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //    self.pathSwear=[[NSBundle mainBundle] pathForResource:@"swearList" ofType:@"plist"];
    //    self.swearDy=[NSArray arrayWithContentsOfFile:self.pathSwear];
    //    self.pathCountry=[[NSBundle mainBundle] pathForResource:@"countryList" ofType:@"plist"];
    //    self.countryDy=[NSArray arrayWithContentsOfFile:self.pathCountry];
    self.currentSection=-1;
    NSLog(@"viewDidLoad");
    
    //设置table的一些参数
    self.tableView.backgroundView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"background.jpg"]];
    self.tableView.sectionIndexColor=[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1];
    self.tableView.sectionIndexTrackingBackgroundColor=[UIColor colorWithRed:0.50196081399917603 green:0.25098040699958801 blue:0.0 alpha:0.6];
    
    //加载fireImage;
    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"]];
}
-(void)viewWillAppear:(BOOL)animated{
    NSLog(@"viewWillAppear");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return [self.countryDy count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    NSInteger countryID=[self getCountryIdBySession:section];
    return  [[self getArrayByCountryId:countryID] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"swearInfo";
    ButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if(cell==nil){
        cell=[[ButtonCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    if(self.currentSection!=indexPath.section){
        //进入新的section了
        NSInteger countryID=[self getCountryIdBySession:indexPath.section];
        self.array=[[self getArrayByCountryId:countryID] mutableCopy];
    }
    cell= [self CellSetedByRow:indexPath.row withArray:self.array andCell:cell];
    //  修改 右边 导航栏背景色  残疾法
    //    for(UIView *view in [tableView subviews])
    //    {
    //
    //        if([[[view class] description] isEqualToString:@"UITableViewIndex"])
    //        {
    //
    ////
    ////            if(indexPath.row%2){
    ////            [view setBackgroundColor:[UIColor yellowColor]];
    ////            }else{
    ////            [view setBackgroundColor:[UIColor blueColor]];
    ////            }
    ////
    //////            [view setFont:[UIFont systemFontOfSize:14]];
    //        }
    //    }
    return cell ;
}

- (NSArray *)getArrayByCountryId:(NSInteger) countryid{
    //根据国家ID获取对应粗口数组
    NSMutableArray * tempArray=[[NSMutableArray alloc]init];
    for(CountryVO *a  in self.swearDy){
        if([a.countryId integerValue]==countryid){
            [tempArray addObject:a];
            
        }
    }
    return tempArray;
}

- (NSInteger)getCountryIdBySession:(NSInteger) section{
    //通过session获得国家id
    NSInteger result=0;
    CountryVO * tempD=(CountryVO *)[self.countryDy objectAtIndex:section];
    result =[tempD.countryId integerValue];
    return  result;
    
}

- (NSString *)CountryNameBySession:(NSInteger) section{
    //通过session获得国家名
    NSString *result=0;
    CountryVO *tempD=(CountryVO *)[self.countryDy objectAtIndex:section];
    result = tempD.countryName;
    return  result;
}
//
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//
//
//}

#define BASEHEIGHT 76 //cell初始状态高度
#define PERHEIGHT 20 //每次行增加距离
#define DEFAULT 27 //初始name 高度
#define rowSize 22 //每行字节数
#define DEFAULTDSCRIBE 24  //出状态DSCRIBE 高度

- (ButtonCell *)CellSetedByRow:(NSInteger)row withArray:(NSArray *)a andCell:(ButtonCell *)cell{
    //根据行号,对应的数组,和CELL设置CELL。
    SwearVO * swearVO= (SwearVO *)[a objectAtIndex:row];
    //        UILabel * labCountry=(UILabel *)[cell viewWithTag:-1];
    //        UILabel * labName=(UILabel *)[cell viewWithTag:-2];
    //        UILabel * labLevel=(UILabel *)[cell viewWithTag:-3];
    ////        UILabel * labImagePath=(UILabel *)[cell viewWithTag:-4];
    //        UILabel * labdescribe=(UILabel *)[cell viewWithTag:-5];
    //        UIButton *bt=(UIButton *)[cell viewWithTag:-6];
    
    //    ((UILabel *)[cell viewWithTag:10]).text=@"这里是Cellview";
    //      简单说明下想对cell直接丢text[虽然我估计你不会这么操作,而且这么操作会让子VIEW不显示]
    //      是无法使用cell.text的
    //      而是使用cell viewWithTag:x
    //      这里很有趣cell能通过自己的viewWithTag 来获取自己顶层的view[此view无法循环viweWithTag]。然后进行操作。
    
    //    UITableViewCell * b=((UITableViewCell *)[cell viewWithTag:10]);
    //    ((UILabel *)[b viewWithTag:1]).text=@"so funy";
    
    //赋值
    cell.idlb.text=swearVO.swearId;
    cell.describe.text=swearVO.swearIntroduce;
    cell.button.tag=[swearVO.swearId integerValue];
    if([self.fireImages objectAtIndex:[swearVO.fireLever integerValue]-1]){
        cell.fire.image=[self.fireImages objectAtIndex:[swearVO.fireLever integerValue]-1];
    }
    
    //计算cell变化 start
    int line;
    if(swearVO.swearName.length%rowSize){
        line =(swearVO.swearName.length/rowSize)+1;
    }else{
        line=(swearVO.swearName.length/rowSize);
    }
    
    

    NSString *str=swearVO.swearName ;

    
    CGSize size=[str sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:CGSizeMake(210.0f,1000.0f ) lineBreakMode:NSLineBreakByWordWrapping];
        CGSize size2=[@"1" sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:CGSizeMake(210.0f,1000.0f ) lineBreakMode:NSLineBreakByWordWrapping];
    
    //name frame修改
    CGRect rect=cell.name.frame;
    rect.size.height=size.height;
    int move=size.height-size2.height;
    cell.name.frame=rect;
    
    //name内容增加"\n"换行符 那个方法用了递归

    cell.name.text=str;

    
    //修改Dscribe位置
    CGRect rectDscribe;
    rectDscribe=cell.describe.frame;
//    NSLog(@"%f!!!!!!!!",rectDscribe.origin.y);
    rectDscribe.origin.y=DEFAULTDSCRIBE+move;
    cell.describe.frame=rectDscribe;
    //    cell.name.bounds=rectBound;
    
    

//    NSLog(@"%d|%f|%f",[cell.name numberOfLines], cell.name.bounds.size.height, cell.name.frame.size.height);
    
    
    
    
    //   labCountry.text=swearVO.countryId;
    //    labName.text=swearVO.swearName;
    //   labLevel.text=swearVO.fireLever;
    //    labdescribe.text=    cell.describe.text=swearVO.swearIntroduce;
    //    bt.tag=[swearVO.swearId integerValue];
    
    //    if(row%2){
    //        cell.contentView.backgroundColor=[UIColor yellowColor];
    //    }else{
    //        cell.contentView.backgroundColor=[UIColor yellowColor];
    //    }
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return [self CountryNameBySession:section];
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height;
    NSInteger countryID=[self getCountryIdBySession:indexPath.section];
    NSArray *array=[[self getArrayByCountryId:countryID] mutableCopy];
    SwearVO *swearVO=(SwearVO *)[array objectAtIndex:indexPath.row];
    int line=(swearVO.swearName.length/(rowSize+1))+1;
    height=BASEHEIGHT+(line-1)*PERHEIGHT;
    return height;
    
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self srceenShot];
    NSInteger countryID=[self getCountryIdBySession:indexPath.section];
    self.array=[[self getArrayByCountryId:countryID] mutableCopy];
    SwearVO *swearVO=(SwearVO *)[self.array objectAtIndex:indexPath.row];
    [self shareWithText:swearVO.swearName];
    
    
}

- (void)shareWithText:(NSString *)text{
    NSArray *activityItems;
    self.text=text;
    if(self.image){
        activityItems=@[self.text,self.image];
    }else{
        activityItems=@[self.text];
    }
    UIActivityViewController *avc=[[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    [self presentViewController:avc animated:YES completion:nil];
    
    
}

- (void)srceenShot{
    //    UIGraphicsPushContext(UIGraphicsGetCurrentContext());
    UIGraphicsPushContext(UIGraphicsGetCurrentContext());
    UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    self.image=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIGraphicsPopContext();
    //    UIGraphicsPopContext();
    
}


- (IBAction)btVideoPressed:(UIButton *)sender {
    //    UITableViewCell *cell=(UITableViewCell *)sender.superview;
    NSLog(@"%d",sender.tag);
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    //用于设置sectionIndexTitle
    //返回要为一个内容为NSString 的NSArray 里面存放section title;
    //默认情况下 section Title根据顺序对应 section 【如果不写tableView: sectionForSectionIndexTitle: atIndex:的话】
    NSMutableArray* a=[NSMutableArray array];
    for(CountryVO *c in self.countryDy){
        [a addObject: [c.countryName substringToIndex:1]];
    }
    
    
    //    self.tableView.sec
    //    self.tableView.sectionIndexTrackingBackgroundColor=[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
    
    //    return b=@[@"1",@"2"];
    return a;
}


- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    //传入 section title 和index 返回其应该对应的session序号。
    //一般不需要写 默认section index 顺序与section对应。除非 你的section index数量或者序列与section不同才用修改
    return index;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIImageView *result=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"title_bg.png"]];
    UILabel *content=[[UILabel alloc]initWithFrame:CGRectZero];
    content.frame = CGRectMake(10.0, 0.0, 300.0, 18.0);
    content.font=[UIFont systemFontOfSize:15];
    content.backgroundColor=[UIColor clearColor];
    content.textColor=[UIColor whiteColor];
    
    content.text=((CountryVO *)[self.countryDy objectAtIndex:section]).countryName;
    [result addSubview:content];
    return result;
    
}

//根据传入的string增补 "\n"
//注:【在stroyboard里面设置lable行数为0,既可自动换行】
//-(NSString *)stringWillNByString:(NSString *)str line:(NSInteger)lineNum{
//    NSString *firstStr;
//    NSString *secondStr;
//    if(str.length>rowSize){
//        firstStr=[str substringToIndex:rowSize];
//        firstStr=[firstStr stringByAppendingString:@"\n"];
//        secondStr=[str substringFromIndex:rowSize];
//        [self stringWillNByString:secondStr line:lineNum-1];
//        return [NSString stringWithFormat:@"%@%@",firstStr,secondStr];
//    }else{
//        secondStr=str;
//        return secondStr;
//    }
//    
//    
//}

@end
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics