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")
}
}
letfoundRange = self.mutableString.range(of: textToFind)
需要 String,但我已将其声明为 NSMutableAttributedString,因此我可以为标签的特定部分添加权重。
我想不通。有人可以帮我解决吗?我真的很感激。
最佳答案
NSMutableAttributedString
有一个名为 string
的属性。要访问它并允许搜索,请使用 yourMutableAttributedString.string
作为参数。
关于swift - 部分标签可点击并同时加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41797916/