我有一个属性字符串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
现在我想将文本的某些部分设置为UIButton
,如何执行此操作?
示例1
示例2
我需要让蓝色文字响应触摸,并运行特定功能,例如UIButton
。
非常感谢帮助,谢谢。
答案 0 :(得分:11)
假设您有UILabel
文字“ abc 123”,并且您希望“ abc ”充当UIButton
。
UITapGestureRecognizer
添加到UILabel
。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)) {
// ...
}
}
答案 1 :(得分:10)
您要做的是使用带有文本视图的属性字符串来创建一个充当按钮的链接。
let attributedString = NSMutableAttributedString(string: "Some string with link", attributes: [<attributes>])
然后将其中的一部分设置为链接,并使用文本视图的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
最后在文本视图委托中,我们将检查方案并执行一些操作。
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
if URL.scheme == "CUSTOM" {
// Do your button actions here
}
return true
}
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
}
}
答案 2 :(得分: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)
编辑:
如果你想摆脱下划线,最好的方法是遵循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)};
}
}
你可以删除这个
NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)
来自属性
答案 3 :(得分:2)
我的想法是使用TTTAttributedLabel这样的库并以这种方式使用它:
请考虑以下字符串“我想要可触摸此处”,其中此处将在触摸时执行segue。
TTTAttributedLabel
(UILabel
子类),并将文本内容放入其中,就像它是UILabel
一样。将其代表设置为自己。然后,以这种方式添加单词的链接:目标C
NSRange rangeWord = [attributedLabel.text rangeOfString:@"here"];
[attributedLabel addLinkToURL:[NSURL URLWithString:@"anActionOnClickHere"] withRange:rangeUser];
夫特
NSRange rangeWord = attributedLabel.text.rangeOfString("here")
attributedLabel.addLinkToURL(NSURL(string: "anActionOnClickHere"), withRange:rangeUser)
目标C
- (void)attributedLabel:(__unused TTTAttributedLabel *)label
didSelectLinkWithURL:(NSURL *)url {
NSString *urlToString = [url absoluteString];
if ([urlToString containsString:@"anActionOnClickHere"]) { //perform segue for example
[self performSegueWithIdentifier:@"hereSegue" sender:self];
}
}
夫特
func attributedLabel(label: TTTAttributedLabel!, didSelectLinkWithURL url: NSURL!) {
NSString *urlToString = url.absoluteString()
if (urlToString.containsString("anActionOnClickHere")) { //perform segue for example
self.performSegueWithIdentifier("hereSegue",sender:self)
}
}
使用默认链接样式,您将获得您正在寻找的蓝色。