检测UILable中的文本给电话号码加上下划线并添加拨打电话事件,这种需求在显示物流信息时经常遇到,具体参考代码如下所示:
/** 设置信息,检测是否有有手机号。有则添加拨打电话事件 */
func setTextInfoToPhone(labInfo:UILabel,WithText text:String){
let stringRange:NSRange = NSRange.init(location: 0, length: NSString.init(string: text).length)
//匹配号码
let strRegex = "\\d{3,4}[-]?\\d{7,8}"
let regexps:NSRegularExpression? = try! NSRegularExpression.init(pattern: strRegex, options: NSRegularExpression.Options(rawValue: 0))
if regexps != nil {
regexps?.enumerateMatches(in: text,
options: NSRegularExpression.MatchingOptions.init(rawValue: 0),
range: stringRange,
using: { (result:NSTextCheckingResult?, flags:NSRegularExpression.MatchingFlags, _) in
//可能为电话号码的字符串及其所在位置
let phoneRange:NSRange = (result?.range)!
_phone = NSString.init(string: text).substring(with: phoneRange)
//设置文本中的电话号码显示为蓝色
let attributeStriung:NSMutableAttributedString = NSMutableAttributedString.init(string: text)
let dicAttr:[NSAttributedString.Key:Any] = [
NSAttributedString.Key.foregroundColor:UIColor.init().colorFromHexInt(hex: 0x3d45fb),
NSAttributedString.Key.underlineStyle:1
]
attributeStriung.addAttributes(dicAttr, range: phoneRange)
labInfo.attributedText = attributeStriung
//点击拨打电话
var phoneControl:UIControl? = labInfo.viewWithTag(1234) as? UIControl
if phoneControl == nil {
phoneControl = UIControl.init(frame: labInfo.boundingRect(forCharacterRange: phoneRange))
phoneControl?.tag = 1234
phoneControl?.isUserInteractionEnabled = true
phoneControl?.addTarget(self, action: #selector(callPhoneAction(sender:)), for: UIControl.Event.touchUpInside)
labInfo.addSubview(phoneControl!)
}
})
}
else{
labInfo.text = text
}
}
具体效果图如下: