swift - 部分标签可点击并同时加粗

标签 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")

    }

}

letfoundRange = self.mutableString.range(of: textToFind) 需要 String,但我已将其声明为 NSMutableAttributedString,因此我可以为标签的特定部分添加权重。

我想不通。有人可以帮我解决吗?我真的很感激。

最佳答案

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

关于swift - 部分标签可点击并同时加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41797916/

相关文章:

swift - 如何在 Xcode 6 中对齐标签下的按钮?

swift - 为 UILabel 创建插入空间

ios - 快速组合 : Unexpected backpressure behaviour with zip operator

ios - 设置 Google Analytics iOS Swift

python - 在某些步骤后加入字符串

c - 在 C 中使用 sscanf 从文件中读取多行字符串

ios - UILabel 周围的两条水平线

ios - 在初始化时创建和编译自定义 Metal 着色器

ios - 在 SWIFT 中将 NSDate 转换为具有特定时区的字符串

javascript - 查找仅具有部分已知值的字符串