您的位置:首页 > 移动开发 > IOS开发

IOS 自定义流式LabelView

2014-05-15 10:26 399 查看
一般情况下,所谓流式布局,大都是瀑布流图片,是竖向排版布局的,但是有时候我们会遇到横向排版布局的Label,鄙人不才,自己按照需要自定义了这样的一个view,话不多说,上代码:

实例化这个view,传入一个数组和需要的font

- (id)initWithFrame:(CGRect)frame WithArr:(NSArray *)aArr WithFont:(UIFont *)aFont;

{

    self = [super initWithFrame:frame];

    if (self) {

        //初始化

        CGFloat x = 0;

        CGFloat y = 0;

        

        for (int i = 0; i < [aArr count]; i ++) {

            NSString *str = [aArr objectAtIndex:i];

            CGSize size;

           //IOS6 和IOS7 方法不同

            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f) {

                size = [str sizeWithAttributes:@{NSFontAttributeName: aFont}];

            }

            else

            {

                size = [str sizeWithFont:aFont];

            }

           // x 即为每个label 的右边边缘 ,当这一行放不下这个label的时候,另起一行

            x = x + size.width + 10;

            if (x > frame.size.width) {

                x = size.width + 10;

                y += size.height;

            }

            NSLog(@"--------%f-----%f-", x,y);

            

            UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(x - size.width - 10, y, size.width, size.height)];

            [lab setText:str];

            [lab setBackgroundColor:[UIColor clearColor]];

            [lab setFont:aFont];

            [self addSubview:lab];

      

            

        }

        

        

        

        self.height = y + 10;

        

        

    }

    return self;

}

//在外面调用这个方法,来让这个view自适应高度

- (void)resetFrame

{

    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.height);

}

目前就是这样,以后遇见有额外需求的,会另外补充。欢迎各位批评指点,共同进步。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios uilabel 布局