【问题标题】:Add UITapGestureRecognizer to NSAttributed Text with a range将 UITapGestureRecognizer 添加到具有范围的 NSAttributed Text
【发布时间】:2014-11-20 14:14:48
【问题描述】:

我有一个这样设置的属性字符串:

var range = (showStr as NSString).rangeOfString(spellingStr)
var attributedString = NSMutableAttributedString(string:showStr)
attributedString.addAttribute(NSForegroundColorAttributeName, value: ezGreen, range: range)

我想在我设置为绿色的范围内添加一个点击手势。

是否有用于触摸的属性?我如何为spellingStr 部分设置点击手势?

编辑

该标签和字符串的所有代码如下:

var showStr:NSString = "Showing results for \(searchT)."
println("SearchTerm:\(searchT)")
showingLabel.textColor = .blackColor()

var range = (showStr as NSString).rangeOfString(searchT)
var attributedString = NSMutableAttributedString(string:showStr)
attributedString.addAttribute(NSForegroundColorAttributeName, value: ezGreen , range: range)

showingLabel.attributedText = attributedString
showingLabel.font = UIFont.systemFontOfSize(17)
showingLabel.numberOfLines = 0
showingLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
var showHeight:CGFloat = heightForView(showingLabel.text!, UIFont.systemFontOfSize(17), maxLabelWidth)
showingLabel.frame = CGRectMake(20, heightOfCor, maxLabelWidth, showHeight)
heightOfCor += showHeight
bgBlack.addSubview(showingLabel)

【问题讨论】:

标签: ios objective-c swift ios8


【解决方案1】:

我通过创建一个 UIButton 并将其设置为该文本行的确切框架来完成它。

这是一个如何在objective-c中执行的示例:

NSRange range = [self.textView.text rangeOfString:@"The string of text you want to tap"];
self.textView.selectedRange = range;
UITextRange *textRange = [self.textView selectedTextRange];
CGRect textRect = [self.textView firstRectForRange:textRange];
CGRect convertedRect = [self.view convertRect:textRect fromView:self.textView];

UIButton *button = [[UIButton alloc]initWithFrame:convertedRect];
[button setBackgroundColor:[UIColor clearColor]];
[button addTarget:self action:@selector(textTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[self.view bringSubviewToFront:button];

注意:在调用它之前,您应该已经设置了属性字符串并将其添加到您的 UITextView。另外,请确保您允许在 textView 中进行选择(但如果您不想要高亮等,请禁用 userInteraction)

【讨论】:

    猜你喜欢
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多