gpt4 book ai didi

ios - 获取 UILabel 中第一行的字符串

转载 作者:行者123 更新时间:2023-12-02 11:03:21 29 4
gpt4 key购买 nike

我在 UILabel 中有一些文本。我想获取字符串变量中第一个标签的文本。

例如:

label.text = @"You make an object by creating an instance of a particular class. You do this by allocating the object and initializing it with acceptable default values. When you allocate an object, you set aside enough memory for the object and set all instance variables to zero. Initialization sets an object’s initial state—that is, its instance variables and properties—to reasonable values and then returns the object. The purpose of initialization is to return a usable object. You need to both allocate and initialize an object to be able to use it.";

现在我想获取UILabel中第一行的文本。

最佳答案

1.添加CoreText.framework。 2. 导入#import CoreText/CoreText.h>。然后使用下面的方法 -

-(NSArray *)getLinesArrayOfStringInLabel:(UILabel *)label
{
NSString *text = [label text];
UIFont *font = [label font];
CGRect rect = [label frame];

CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
[attStr addAttribute:(NSString *)kCTFontAttributeName value:( id)myFont range:NSMakeRange(0, attStr.length)];

CFRelease(myFont);

CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);

CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000));

CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);

NSArray *lines = ( NSArray *)CTFrameGetLines(frame);

NSMutableArray *linesArray = [[NSMutableArray alloc]init];

for (id line in lines)
{
CTLineRef lineRef = ( CTLineRef )line;
CFRange lineRange = CTLineGetStringRange(lineRef);
NSRange range = NSMakeRange(lineRange.location, lineRange.length);

NSString *lineString = [text substringWithRange:range];

CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0]));
CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0]));

//NSLog(@"''''''''''''''''''%@",lineString);
[linesArray addObject:lineString];

}
[attStr release];

CGPathRelease(path);
CFRelease( frame );
CFRelease(frameSetter);


return (NSArray *)linesArray;
}

我从下面的网址找到了这个答案 - How to get text from nth line of UILabel?

NSString *firstLineString = [[self getLinesArrayOfStringInLabel:yourLabel] objectAtIndex:0];

关于ios - 获取 UILabel 中第一行的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30435406/

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