标签的一部分同时可点击和加粗

时间:2017-01-23 01:08:23

标签: swift string uilabel clickable nsmutableattributedstring

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,因此我可以为标签的特定部分添加权重。

我无法弄明白。有人可以帮我解决这个问题吗?我真的很感激。

1 个答案:

答案 0 :(得分:0)

NSMutableAttributedString有一个名为string的属性。要访问它并允许搜索,请使用yourMutableAttributedString.string作为参数。