IOS UIlabel点击全文扩展

释放双眼,带上耳机,听听看~!

传入初始化frame之后的lab,返回的是每行的string。

通过计算最后一行string的rect得到全文/扩展btn的x,y值

-(NSArray*)getSeparatedLinesFromLabel:(UILabel *)label

{

   NSString *text= [label text];

   UIFont
  *font = [label font];

   CGRect   rect = [labelframe];

   

   CTFontRefmyFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [fontpointSize], NULL);

   NSMutableAttributedString*attStr = [[NSMutableAttributedString alloc] initWithString:text];

   [attStraddAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0,attStr.length)];

   

   CTFramesetterRefframeSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);

   

   CGMutablePathRefpath = CGPathCreateMutable();

   CGPathAddRect(path,NULL, CGRectMake(0,0,rect.size.width,100000));

   

   CTFrameRefframe = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);

   

   NSArray *lines= (__bridge NSArray *)CTFrameGetLines(frame);

   NSMutableArray*linesArray = [[NSMutableArray alloc]init];

   for (id line inlines)

   {

     CTLineReflineRef = (__bridge CTLineRef )line;

     CFRangelineRange = CTLineGetStringRange(lineRef);

     NSRange range =NSMakeRange(lineRange.location, lineRange.length);


     NSString*lineString = [text substringWithRange:range];

     [linesArrayaddObject:lineString];

   }

   return (NSArray*)linesArray;

}

 

如下所示

btn紧随最后一行文字的后面

NSArray * arr = [selfgetSeparatedLinesFromLabel:_lab];

   CGRect rect =[[arr lastObject] boundingRectWithSize:CGSizeMake(SREENWIDTH, MAXFLOAT)options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOriginattributes:@{NSFontAttributeName:[UIFont
systemFontOfSize:15]} context:nil];

   UIButton * btn= [UIButton buttonWithType:UIButtonTypeCustom];

   btn.frame = CGRectMake(rect.size.width+10,(arr.count-1)*(rect.size.height), 50, rect.size.height);

   [btn setTitle:@"全文" forState:UIControlStateNormal];

   [btnsetTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

   [btn addTarget:selfaction:@selector(method) forControlEvents:UIControlEventTouchUpInside];

   _lab.frame = CGRectMake(0,60, SREENWIDTH, CGRectGetMaxY(btn.frame));

  _lab.userInteractionEnabled = YES;

   [self.viewaddSubview:_lab];

   [_labaddSubview:btn];

截取的文字长度,替换的文字自行处理

点击全文把之前的text重新赋值给lab ,重新计算frame即可

 

人已赞赏
iOS文章

ios UITableView设置 setSeparatorInset:UIEdgeInsetsZero不起作用的解决办法

2020-3-31 6:47:21

iOS文章

IOS UIWebView 背景透明

2020-3-31 8:02:00

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索