import Foundation
import UIKit
extension NSMutableAttributedString {
@discardableResult
public func setAsLink(textToFind: NSMutableAttributedString, linkURL: String) -> Bool {
let foundRange = self.mutableString.range(of: textToFind)
if foundRange.location != NSNotFound {
self.addAttribute(NSLinkAttributeName, value: linkURL, range: foundRange)
return true
}
return false
}
}
@IBDesignable
class SignUpLabel: UILabel {
override func layoutSubviews() {
super.layoutSubviews()
let normalText = "Don't have an account yet? "
let normalString = NSMutableAttributedString(string: normalText)
let boldText = "Sign up now!"
let attrs = [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14)]
let attributedString = NSMutableAttributedString(string: boldText, attributes: attrs)
normalString.append(attributedString)
self.attributedText = normalString
normalString.setAsLink(textToFind: attributedString, linkURL: "http://www.someaddress.com")
}
}
let foundRange = self.mutableString.range(of: textToFind)
需要String,但我已将其声明为NSMutableAttributedString,因此我可以为标签的特定部分添加权重。
我无法弄明白。有人可以帮我解决这个问题吗?我真的很感激。
答案 0 :(得分:0)
NSMutableAttributedString
有一个名为string
的属性。要访问它并允许搜索,请使用yourMutableAttributedString.string
作为参数。