以字符进行截断,免得出现半个字符

来源:互联网 发布:阿里云是邮箱吗 编辑:程序博客网 时间:2024/06/04 19:41
-(CGSize)sizeUtilForTitle:(NSString *)title{    if (NSFoundationVersionNumber<=NSFoundationVersionNumber_iOS_6_1) {        return [title sizeWithFont:self.titleLabel.font];    }else{        return [title sizeWithAttributes:@{NSFontAttributeName:self.titleLabel.font}];    }}//以字符进行截断,免得出现半个字符    CGSize size;    NSString *tempString=nil;    size = [self sizeUtilForTitle:title];    CGSize titleSize = self.titleLabel.bounds.size;    if (size.width>titleSize.width) {        int firstCompare = 0;        int compare = 0;        int currentLength = 8;        do {            tempString = [title substringToIndex:currentLength];            size = [self sizeUtilForTitle:tempString];            compare = size.width<titleSize.width?-1:1;            if (compare==0) {                break;            }                        if (firstCompare*compare>0) {                currentLength-=firstCompare;                continue;            }else if (firstCompare*compare<0){                currentLength+=firstCompare;                break;            }            if (firstCompare==0) {                firstCompare = compare;                currentLength -=compare;            }                    } while (YES);        self.titleLabel.text = [title substringToIndex:currentLength];            }else{        self.titleLabel.text = title;    }
对于单行文字,其实只要对UILabel只要设置numberOfLines大于1,并且lineBreakMode为NSLineBreakByCharWrapping,就可以自动做到以上效果了,以上处理显得有点多余,不过既然写了出来,就记录一下吧。
0 0