打开UILabel的某些部分,使其像UIButton一样? [英] Turn some parts of UILabel to act like a UIButton?

查看:66
本文介绍了打开UILabel的某些部分,使其像UIButton一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an attributed string UILabel, I was able to color some parts of the text

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

现在我想使文本的某些部分可轻按,例如UIButton,该怎么做?

Now I want to make some parts of the text tappable, like a UIButton, how to do this ?

示例1

示例2

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

I need to have blue text to be responding to touch, and to run a specific function, like a UIButton. help is really appreciated, thanks.

推荐答案

我建议您尝试一下该库

https://github.com/null09264/FRHyperLabel

很棒的库,易于使用,并且几乎没有内置示例供您试用.在Objective-c和Swift中都有示例

Great library, easy to use and has few built in examples for you to try out. Examples are in both Objective-c and 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)

如果要消除下划线,最好的方法是遵循DeyaEldeen在评论中提供的建议.

If you want to get rid of the underline, best way to do this is to follow the advice that DeyaEldeen gave in the comment.

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

If you go to the .m file of FRHyperLabel, go to this method

- (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)};
    }
}

您可以删除此

NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)

从属性

这篇关于打开UILabel的某些部分,使其像UIButton一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆