gpt4 book ai didi

iphone - 将按钮作为 subview 放置在 UILabel/UITextView 最后一个字符的旁边

转载 作者:可可西里 更新时间:2023-11-01 04:44:25 26 4
gpt4 key购买 nike

我已经使用了四个 UITextview 来放置每个段落。现在我想为每个 UITextview 添加一个 UIButton 作为 subview 。

我意识到用框架 CGRectMake(textview.frame.width-50,textview.frame.height-20,50,20) 创建 subview 不是一个理想的解决方案,因为句子可能在任何地方结束,我的意思是任何段落的最后一个字符都可以在任何地方结束,但它的位置不是恒定的。

所以最重要的是,我想在 UITextView 中添加 UIButton,就在 lats 单词旁边。我该怎么做?

任何解决方案将不胜感激。 :)

最佳答案

没那么简单。使用:

CGSize sizeOfString = [string sizeWithFont:self.aTextView.font constrainedToSize:self.aTextView.frame.size];

您可以获得给定字符串的 CGSize。但是,给出整个字符串,将导致大小等于您的 UITextView 大小(因此,右下角)

您必须在每个 UITextField 的最后一行使用此方法...这是困难的部分。自动换行由 CoreText、UITextView 或 UILabel 完成,不会为您提供有关单行、位置等的信息。

类似的你得自己计算(代码不是很干净,如果你理解有问题,我稍后会帮助你):

NSAttributedString* text = self.aTextView.attributedText;
CTFramesetterRef fs =
CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)text);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0,0,self.aTextView.frame.size.width - 16,100000)); // why the -16? the frame should be the REAL TEXT FRAME, not the UITextView frame. If you look, there is a space between the view margin and the text. This is the baseline. Probably there is a method to calculate it programatically, but I can't check now. In my case it seems like 8px (*2)
CTFrameRef f = CTFramesetterCreateFrame(fs, CFRangeMake(0, 0), path, NULL);
CTFrameDraw(f, NULL);

NSRange lastRange;
NSArray* lines = (__bridge NSArray*)CTFrameGetLines(f);

id lastLineInArray = [lines lastObject];
CTLineRef theLine = (__bridge CTLineRef)lastLineInArray;
CFRange range = CTLineGetStringRange(theLine);
lastRange.length = range.length;
lastRange.location = range.location - 1;
NSLog(@"%ld %ld", range.location, range.length);

CGPathRelease(path);
CFRelease(f);
CFRelease(fs);

// this is the last line
NSString *lastLine = [self.aTextView.text substringWithRange:lastRange];

现在,您可以使用:

CGSize sizeOfString = [lastLine sizeWithFont:self.aTextView.font constrainedToSize:self.aTextView.frame.size];

您将获得字符串的宽度和高度,然后是按钮的最终位置(对于 y 位置:从 lines 数组中获取的行数 count * 字符串高度)

编辑:关于 UITextView 中左侧空间的注释(此行中有 -16 的原因)

CGPathAddRect(path, NULL, CGRectMake(0,0,self.aTextView.frame.size.width - 16,100000));

发生这种情况是因为文本实际上并不在 UITextView 内部,而是在其 subview 之一内部:一个添加了插图的 UIWebDocumentView(私有(private)类)。经过一些搜索,我找不到任何方法来获取(合法地)这个插入的值,这是将正确的 rect 传递给 CGPathAddRect() 函数所必需的。您可以进行一些测试以确保它始终为 8pt :-) 或切换到没有该内容插入的 UILabel

关于iphone - 将按钮作为 subview 放置在 UILabel/UITextView 最后一个字符的旁边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14357240/

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