1.核心代码,找到电话号码的位置
#pragma mark-<获取电话号码的坐标>
+ (CGRect)boundingRectForCharacterRange:(NSRange)range andLable:(UILabel *)lable lableSize:(CGSize)lableSize{
// NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:contentStr];
// NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
// paraStyle.lineSpacing = 6;
// NSDictionary *attrs =@{NSFontAttributeName : [UIFont systemFontOfSize:12.0], NSParagraphStyleAttributeName : paraStyle};
// [attributeString setAttributes:attrs range:NSMakeRange(0, contentStr.length)];
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:lable.attributedText];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[textStorage addLayoutManager:layoutManager];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:lableSize];
textContainer.lineFragmentPadding = 0;
[layoutManager addTextContainer:textContainer];
NSRange glyphRange;
[layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange];
CGRect rect = [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];
// CGFloat yOfset = rect.origin.y;
// rect.origin.y = yOfset + 3;
return rect;
}
2.用法示例
{ // 添加拨打电话
self.tipsLabel.userInteractionEnabled = YES;
[self.view layoutIfNeeded];
NSRange range = [_tipsLabel.text rangeOfString:@"4006668800"];
UIControl *phoneControl = [[UIControl alloc] initWithFrame:[ZYTools boundingRectForCharacterRange:range andLable:self.tipsLabel lableSize:self.tipsLabel.frame.size]];
phoneControl.tag = 1234;
[phoneControl addTarget:self action:@selector(phoneLink) forControlEvents:UIControlEventTouchUpInside];
[_tipsLabel addSubview:phoneControl];
}
#pragma mark-点击拨打电话
- (void)phoneLink{
NSString *str = [NSString stringWithFormat:@"tel:%@",CustomerServiceTelephone];
dispatch_async(dispatch_get_main_queue(), ^(){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
});
}
3.注意label的attributedText一定要设置字体大小
- (UILabel *)tipsLabel
{
if (!_tipsLabel) {
_tipsLabel = [[UILabel alloc] init];
_tipsLabel.text = @"1、请输入正确的运营商服务密码,如果忘记请点击\"忘记密码\"\n2、运营商认证需要2-3分钟,请耐心等待\n3、如果重置密码失败,请拨打客服热线:4006668800";
_tipsLabel.font = UIFONT_12;
_tipsLabel.numberOfLines = 0;
_tipsLabel.textColor = colorWith(@"#939ca5");
_tipsLabel.textAlignment = NSTextAlignmentLeft;
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.lineSpacing = 6;
NSDictionary *dict = @{NSParagraphStyleAttributeName : paraStyle};
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:_tipsLabel.text attributes:dict];
NSRange range = [_tipsLabel.text rangeOfString:@"4006668800"];
[attr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#FB6F5C"] range:range];
[attr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12.0] range:NSMakeRange(0, _tipsLabel.text.length)];
_tipsLabel.attributedText = attr;
}
return _tipsLabel;
}