gpt4 book ai didi

ios - 将 UITapGestureRecognizer 添加到具有范围的 NSAttributed 文本

转载 作者:搜寻专家 更新时间:2023-11-01 06:24:05 25 4
gpt4 key购买 nike

我有一个属性字符串设置如下:

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)

最佳答案

我只是通过创建一个 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)

enter image description here

关于ios - 将 UITapGestureRecognizer 添加到具有范围的 NSAttributed 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27041723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com