转动UILabel的某些部分就像UIButton一样?

Dey*_*een 19 uibutton uilabel ios swift

我有一个属性字符串UILabel,我能够为文本的某些部分着色

let text = "Why did \(event) give \(event2) a 5 stars review? Details here. "
let linkTextWithColor = "Why did"
let range = (text as NSString).rangeOfString(linkTextWithColor)

let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor() , range: range)

labelEvent.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)

现在我想让文本的某些部分可以替换,比如UIButton,如何做到这一点?

例1

例1

例2

例2

我需要有蓝色文本来响应触摸,并运行一个特定的功能,如一个UIButton.非常感谢帮助,谢谢.

Cod*_*ode 11

假设你有一个UILabel带有文本" abc 123",你想要" abc "作为一个UIButton.

  • 计算并存储包含"abc"的矩形.
  • 添加UITapGestureRecognizerUILabel.
  • UILabel被窃听,检查水龙头的矩形范围内.

static func getRect(str: NSAttributedString, range: NSRange, maxWidth: CGFloat) -> CGRect {
    let textStorage = NSTextStorage(attributedString: str)
    let textContainer = NSTextContainer(size: CGSize(width: maxWidth, height: CGFloat.max))
    let layoutManager = NSLayoutManager()       
    layoutManager.addTextContainer(textContainer)
    textStorage.addLayoutManager(layoutManager)     
    textContainer.lineFragmentPadding = 0       
    let pointer = UnsafeMutablePointer<NSRange>.alloc(1)
    layoutManager.characterRangeForGlyphRange(range, actualGlyphRange: pointer)     
    return layoutManager.boundingRectForGlyphRange(pointer.move(), inTextContainer: textContainer)
}

let rect1 = getRect(label.attributedText!, range: NSMakeRange(0, 3), maxWidth: label.frame.width)

label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(MyClass.tappedLabel(_:))))

func tappedLabel(sender: UITapGestureRecognizer) {
    if rect1.contains(sender.locationInView(sender.view)) {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)


Max*_*Max 11

您要做的是使用带有文本视图的属性字符串来创建一个充当按钮的链接.

let attributedString = NSMutableAttributedString(string: "Some string with link", attributes: [<attributes>])
Run Code Online (Sandbox Code Playgroud)

然后将其一部分设置为链接,并使用linkAttributes文本视图的属性自定义其外观.因为这是一个按钮,而不是一个实际的链接,我们只是为链接添加一个虚拟URL,以便我们稍后可以在我们的委托中处理它.

attributedString.setSubstringAsLink(substring: "link", linkURL: "CUSTOM://WHATEVER")
let linkAttributes: [String : AnyObject] = [NSForegroundColorAttributeName : .redColor(), NSUnderlineColorAttributeName : .redColor(), NSUnderlineStyleAttributeName : NSUnderlineStyle.StyleSingle.rawValue]
textView.linkTextAttributes = linkAttributes
textView.attributedText = attributedString
textView.selectable = true
textView.editable = false
textView.userInteractionEnabled = true
Run Code Online (Sandbox Code Playgroud)

最后在文本视图委托中,我们将检查方案并执行一些操作.

func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
    if URL.scheme == "CUSTOM" {
       // Do your button actions here
    }
    return true
}
Run Code Online (Sandbox Code Playgroud)

setSubstringAsLink的扩展:

extension NSMutableAttributedString {
    // Set part of string as URL
    public func setSubstringAsLink(substring substring: String, linkURL: String) -> Bool {
        let range = self.mutableString.rangeOfString(substring)
        if range.location != NSNotFound {
            self.addAttribute(NSLinkAttributeName, value: linkURL, range: range)
            return true
        }
        return false
    }
}
Run Code Online (Sandbox Code Playgroud)


Ada*_*amM 8

我建议你试试这个库

https://github.com/null09264/FRHyperLabel

很棒的图书馆,易于使用,并且很少有内置示例供您试用.示例在Objective-c和Swift中

Swift中的示例

 let str = "This is a random bit of text"
        let attributes = [NSForegroundColorAttributeName: UIColor.blackColor(),
                          NSFontAttributeName: UIFont.systemFontOfSize(15)]
        confirmLabel.attributedText = NSAttributedString(string: str, attributes: attributes)

        let handler = {
            (hyperLabel: FRHyperLabel!, substring: String!) -> Void in

            //action here
        }
        //Step 3: Add link substrings
        confirmLabel.setLinksForSubstrings(["random"], withLinkHandler: handler)
Run Code Online (Sandbox Code Playgroud)

编辑:

如果你想摆脱下划线,最好的方法是遵循DeyaEldeen在评论中给出的建议.

如果您转到FRHyperLabel的.m文件,请转到此方法

- (void)checkInitialization {
    if (!self.handlerDictionary) {
        self.handlerDictionary = [NSMutableDictionary new];
    }

    if (!self.userInteractionEnabled) {
        self.userInteractionEnabled = YES;
    }

    if (!self.linkAttributeDefault) {
        self.linkAttributeDefault = @{NSForegroundColorAttributeName: FRHyperLabelLinkColorDefault,
                                      NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
    }

    if (!self.linkAttributeHighlight) {
        self.linkAttributeHighlight = @{NSForegroundColorAttributeName: FRHyperLabelLinkColorHighlight,
                                        NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以删除它

NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)
Run Code Online (Sandbox Code Playgroud)

来自属性

  • 虽然此链接可能会回答这个问题,但最好在此处包含答案的基本部分并提供参考链接.如果链接的页面发生更改,则仅链接的答案可能会无效. - [来自评论](/ review/low-quality-posts/12789471) (3认同)