不同宽度的标签

作者: Z了个L | 来源:发表于2016-08-01 16:08 被阅读214次

// ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


@end

// ViewController.m

//  心脏类疾病,高血压

/** 字体大小 */
#define FFFont(fontSize) [UIFont systemFontOfSize:fontSize]
/** 屏幕的宽度 */
#define FFScreenW [UIScreen mainScreen].bounds.size.width

#import "ViewController.h"
#import "NSString+Extension.h"

@interface ViewController ()

/** 存放标签的数组 */
@property (nonatomic, strong) NSArray *tagArr;

@end

@implementation ViewController

#pragma mark - 懒加载
- (NSArray *)tagArr {
    if (_tagArr == nil) {
        _tagArr = @[
                    @"乖巧",
                    @"喜欢你",
                    @"纯洁",
                    @"好漂亮",
                    @"脱俗、大方、机灵",
                    @"淑女、秀外慧中、慧指兰心",
                    @"清水芙蓉、活泼机灵",
                    @"古怪、可爱",
                    @"乐观开朗",
                    @"嫁给我",
                    @"大义凛然",
                    @"母仪天下",
                    @"眉清目秀、可爱",
                    @"亭亭玉立",
                    @"闭月羞花",
                    @"楚楚动人",
                    @"国色天香",
                    @"花容月貌",
                    @"美如冠玉",
                    @"冰清玉洁",
                    @"尊重典雅",
                    @"温柔贤慧",
                    @"娴淑善良",
                    @"纤纤有礼",
                    @"上得厅房 下得厨房",
                    @"沉鱼落雁 委婉大方"
                    ];
    }
    return _tagArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    CGFloat basedWidth = 11;
    CGFloat basedHeight = 22;
    // x坐标的边距
    CGFloat marginX = 10;
    // y坐标的边距
    CGFloat marginY = 10;

    CGFloat x = marginX; //x
//    CGFloat x = FFScreenW * 0.5 - 60; //x
    CGFloat y = marginY; //y

    CGFloat w; //宽
    CGFloat h = basedHeight; //高

    for (NSInteger i = 0; i < self.tagArr.count; i++) {

        NSString *str = self.tagArr[i]; //取出标签的内容
        //计算标签内容的大小
        CGSize size = [str sizeWithFont:FFFont(15) maxSize:CGSizeMake(FFScreenW, 22)];
        w = basedWidth + size.width;
        CGFloat maxX = x + w;

        //maxX 超出这行所允许的范围,另起一行
        if (maxX >= (FFScreenW - marginX)) {
            x = marginX;
//            x = FFScreenW * 0.5 - 60;
            y = y + marginY + basedHeight;
        }

        CGRect frame = CGRectMake(x, y, w, h);

        // 创建UILabel对象
        UILabel *label = [UILabel new];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        label.font = FFFont(15);
        label.frame = frame;
        label.layer.cornerRadius = frame.size.height * 0.5;
        label.clipsToBounds = YES;
        label.text = self.tagArr[i];
        label.backgroundColor = [UIColor redColor];

        [self.view addSubview:label];

        x = x + marginX + w;
    }

}

@end


  • 效果图显示:

相关文章

网友评论

    本文标题:不同宽度的标签

    本文链接:https://www.haomeiwen.com/subject/looxsttx.html