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)
需要字符串,但我已将其声明为 NSMutableAttributedString,因此我能够为标签的特定部分添加权重。
我想不通。有人可以帮我修复吗?我真的很感激。
NSMutableAttributedString
有一个名为string
的属性。要访问它并允许搜索,请使用yourMutableAttributedString.string
作为参数。