ios – 在UITextView中选择一个单词

编辑:我想我应该使用UILabel而不是UITextView,因为我不希望突出显示使用系统范围的蓝色和’copy / select all / define’popover.

我正在尝试构建自定义文本视图,我正在寻找正确方法的一些帮助.我是一个iOS n00b,所以主要是寻找有关如何最好地解决问题的想法.

我想构建一个自定义文本视图,具有以下行为:

>视图从小开始.如果它收到一个点击它会增长(动画)为父视图的大小作为模态窗口(左上图,然后右上图)
>在这个大状态中,如果单击一个单词,则单词以某种方式突出显示,并且委托方法称为传递包含被轻敲的字符串的字符串(左下图)

New Text View http://telliott.net/static/NewTextView.png

我怀疑复杂性将在于识别被点击的单词,所以让我们从那里开始.我可以想到几种尝试这种方法

> UILabel子类.添加触摸手势识别器.识别触摸时,以某种方式获取触摸点的(x.y)坐标,查看视图显示的字符串,并根据位置确定必须按下哪个字.然而,我可以通过自动换行很快看到这变得非常复杂.我不确定如何获得触摸的(x,y)坐标(虽然我认为这很简单),或者如何获得每个角色等设备相关的文本宽度.我宁愿不去这条路线,除非有人可以说服我这不会太可怕!
> UIView子类,并通过为每个单词添加UILabel来伪造句子.测量每个UILabel的宽度并自己铺设.这似乎是一种更明智的方法,虽然我担心以这种方式布置文本也比我开始尝试时的想法更难.

有更明智的方法吗?你可以用其他方式检索UILabel中触及的单词吗?

如果我选择选项2,那么我认为动画来自小 – >大文本可能很复杂,因为单词将以有趣的方式包装.所以我想要另一个子视图 – 这次是UITextView – 将句子保持在小状态.将此动画设置为大,然后将其隐藏,同时以每个单词的一个视图显示我的UIView.

任何想法都赞赏.提前致谢 :)

解决方法

更新

由于在CoreText中添加了NSLayoutManager,因此iOS 7更容易实现.如果您正在处理UITextView,则可以将布局管理器作为视图的属性进行访问.在我的情况下,我想坚持使用UILabel,所以你必须创建一个大小相同的布局管理器,即:

NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:labelText];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[textStorage addLayoutManager:layoutManager];
CGRect bounds = label.bounds;
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:bounds.size];
[layoutManager addTextContainer:textContainer];

现在你只需要找到被点击的字符的索引,这很简单!

NSUInteger characterIndex = [layoutManager characterIndexForPoint:location
                                                  inTextContainer:textContainer
                         fractionOfdistanceBetweenInsertionPoints:NULL];

这使得找到这个词本身变得微不足道:

if (characterIndex < textStorage.length) {
  [labelText.string enumerateSubstringsInRange:NSMakeRange(0,textStorage.length)
                                       options:NsstringEnumerationByWords
                                    usingBlock:^(Nsstring *substring,NSRange substringRange,NSRange enclosingRange,BOOL *stop) {
                                      if (NSLocationInRange(characterIndex,enclosingRange)) {
                                        // Do your thing with the word,at range 'enclosingRange'
                                        *stop = YES;
                                      }
                                    }];
}

原始答案,适用于iOS< 7 感谢@JP Hribovsek提供了一些有关此工作的提示,我设法为我的目的解决了这个问题.它感觉有点hacky,对于大型文本可能不会很好,但对于一次一段(这是我需要的),它很好. 我创建了一个简单的UILabel子类,允许我设置插入值:

#import "WWLabel.h"

#define WWLabelDefaultInset 5

@implementation WWLabel

@synthesize topInset,leftInset,bottomInset,rightInset;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.topInset = WWLabelDefaultInset;
        self.bottomInset = WWLabelDefaultInset;
        self.rightInset = WWLabelDefaultInset;
        self.leftInset = WWLabelDefaultInset;
    }
    return self;
}

- (void)drawTextInRect:(CGRect)rect
{
    UIEdgeInsets insets = {self.topInset,self.leftInset,self.bottomInset,self.rightInset};

    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect,insets)];
}

然后我创建了一个包含我的自定义标签的UIView子类,然后在标签上构建了标签中每个单词的文本大小,直到大小超过了点击位置的大小 – 这是被点击的单词.这不是完美的,但现在效果还不错.

然后我使用一个简单的NSAttributedString来突出显示文本:

#import "WWPhoneticTextView.h"
#import "WWLabel.h"

#define WWPhoneticTextViewInset 5
#define WWPhoneticTextViewDefaultColor [UIColor blackColor]
#define WWPhoneticTextViewHighlightColor [UIColor yellowColor]

#define UILabelMagicTopMargin 5
#define UILabelMagicLeftMargin -5

@implementation WWPhoneticTextView {
    WWLabel *label;
    NSMutableAttributedString *labelText;
    NSRange tappedRange;
}

// ... skipped init methods,very simple,just call through to configureView

- (void)configureView
{
    if(!label) {
        tappedRange.location = NSNotFound;
        tappedRange.length = 0;

        label = [[WWLabel alloc] initWithFrame:[self bounds]];
        [label setLineBreakMode:NSLineBreakByWordWrapping];
        [label setNumberOfLines:0];
        [label setBackgroundColor:[UIColor clearColor]];
        [label setTopInset:WWPhoneticTextViewInset];
        [label setLeftInset:WWPhoneticTextViewInset];
        [label setBottomInset:WWPhoneticTextViewInset];
        [label setRightInset:WWPhoneticTextViewInset];

        [self addSubview:label];
    }


    // Setup tap handling
    UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc]
                                               initWithTarget:self action:@selector(handleSingleTap:)];
    singleFingerTap.numberOfTapsrequired = 1;
    [self addGestureRecognizer:singleFingerTap];
}

- (void)setText:(Nsstring *)text
{
    labelText = [[NSMutableAttributedString alloc] initWithString:text];
    [label setAttributedText:labelText];
}

- (void)handleSingleTap:(UITapGestureRecognizer *)sender
{
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        // Get the location of the tap,and normalise for the text view (no margins)
        CGPoint tapPoint = [sender locationInView:sender.view];
        tapPoint.x = tapPoint.x - WWPhoneticTextViewInset - UILabelMagicLeftMargin;
        tapPoint.y = tapPoint.y - WWPhoneticTextViewInset - UILabelMagicTopMargin;

        // Iterate over each word,and check if the word contains the tap point in the correct line
        __block Nsstring *partialString = @"";
        __block Nsstring *linestring = @"";
        __block int currentLineHeight = label.font.pointSize;
        [label.text enumerateSubstringsInRange:NSMakeRange(0,[label.text length]) options:NsstringEnumerationByWords usingBlock:^(Nsstring* word,NSRange wordRange,BOOL* stop){

            CGSize sizeforText = CGSizeMake(label.frame.size.width-2*WWPhoneticTextViewInset,label.frame.size.height-2*WWPhoneticTextViewInset);
            partialString = [Nsstring stringWithFormat:@"%@ %@",partialString,word];

            // Find the size of the partial string,and stop if we've hit the word
            CGSize partialStringSize  = [partialString sizeWithFont:label.font constrainedToSize:sizeforText lineBreakMode:label.lineBreakMode];

            if (partialStringSize.height > currentLineHeight) {
                // Text wrapped to new line
                currentLineHeight = partialStringSize.height;
                linestring = @"";
            }
            linestring = [Nsstring stringWithFormat:@"%@ %@",linestring,word];

            CGSize linestringSize  = [linestring sizeWithFont:label.font constrainedToSize:label.frame.size lineBreakMode:label.lineBreakMode];
            linestringSize.width = linestringSize.width + WWPhoneticTextViewInset;

            if (tapPoint.x < linestringSize.width && tapPoint.y > (partialStringSize.height-label.font.pointSize) && tapPoint.y < partialStringSize.height) {
                NSLog(@"Tapped word %@",word);
                if (tappedRange.location != NSNotFound) {
                    [labelText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:tappedRange];
                }

                tappedRange = wordRange;
                [labelText addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:tappedRange];
                [label setAttributedText:labelText];
                *stop = YES;
            }
        }];        
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple 最新软件的错误和性能问题。
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只有5%的概率会遇到选择运营商界面且部分必须连接到iTunes才可以激活
一般在接外包的时候, 通常第三方需要安装你的app进行测试(这时候你的app肯定是还没传到app store之前)。
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应用变灰了。那么接下来我们看一下Flutter是如何实现的。Flutter中实现整个App变为灰色在Flutter中实现整个App变为灰色是非常简单的,只需要在最外层的控件上包裹ColorFiltered,用法如下:ColorFiltered(颜色过滤器)看名字就知道是增加颜色滤镜效果的,ColorFiltered( colorFilter:ColorFilter.mode(Colors.grey, BlendMode.
flutter升级/版本切换
(1)在C++11标准时,open函数的文件路径可以传char指针也可以传string指针,而在C++98标准,open函数的文件路径只能传char指针;(2)open函数的第二个参数是打开文件的模式,从函数定义可以看出,如果调用open函数时省略mode模式参数,则默认按照可读可写(ios_base:in | ios_base::out)的方式打开;(3)打开文件时的mode的模式是从内存的角度来定义的,比如:in表示可读,就是从文件读数据往内存读写;out表示可写,就是把内存数据写到文件中;
文章目录方法一:分别将图片和文字置灰UIImage转成灰度图UIColor转成灰度颜色方法二:给App整体添加灰色滤镜参考App页面置灰,本质是将彩色图像转换为灰度图像,本文提供两种方法实现,一种是App整体置灰,一种是单个页面置灰,可结合具体的业务场景使用。方法一:分别将图片和文字置灰一般情况下,App页面的颜色深度是24bit,也就是RGB各8bit;如果算上Alpha通道的话就是32bit,RGBA(或者ARGB)各8bit。灰度图像的颜色深度是8bit,这8bit表示的颜色不是彩色,而是256
领导让调研下黑(灰)白化实现方案,自己调研了两天,根据网上资料,做下记录只是学习过程中的记录,还是写作者牛逼
让学前端不再害怕英语单词(二),通过本文,可以对css,js和es6的单词进行了在逻辑上和联想上的记忆,让初学者更快的上手前端代码
用Python送你一颗跳动的爱心
在uni-app项目中实现人脸识别,既使用uni-app中的live-pusher开启摄像头,创建直播推流。通过快照截取和压缩图片,以base64格式发往后端。
商户APP调用微信提供的SDK调用微信支付模块,商户APP会跳转到微信中完成支付,支付完后跳回到商户APP内,最后展示支付结果。CSDN前端领域优质创作者,资深前端开发工程师,专注前端开发,在CSDN总结工作中遇到的问题或者问题解决方法以及对新技术的分享,欢迎咨询交流,共同学习。),验证通过打开选择支付方式弹窗页面,选择微信支付或者支付宝支付;4.可取消支付,放弃支付会返回会员页面,页面提示支付取消;2.判断支付方式,如果是1,则是微信支付方式。1.判断是否在微信内支付,需要在微信外支付。
Mac命令行修改ipa并重新签名打包
首先在 iOS 设备中打开开发者模式。位于:设置 - 隐私&安全 - 开发者模式(需重启)
一 现象导入MBProgressHUD显示信息时,出现如下异常现象Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_MBProgressHUD", referenced from: objc-class-ref in ViewController.old: symbol(s) not found for architecture x86_64clang: error: linker command failed wit
Profiles >> 加号添加 >> Distribution >> "App Store" >> 选择 2.1 创建的App ID >> 选择绑定 2.3 的发布证书(.cer)>> 输入描述文件名称 >> Generate 生成描述文件 >> Download。Certificates >> 加号添加 >> "App Store and Ad Hoc" >> “Choose File...” >> 选择上一步生成的证书请求文件 >> Continue >> Download。
今天有需求,要实现的功能大致如下:在安卓和ios端实现分享功能可以分享链接,图片,文字,视频,文件,等欢迎大佬多多来给萌新指正,欢迎大家来共同探讨。如果各位看官觉得文章有点点帮助,跪求各位给点个“一键三连”,谢啦~声明:本博文章若非特殊注明皆为原创原文链接。