用给定的string查找具有固定宽度和高度的UITextView中的字符数?

在我的应用程序中,如果文本input很大,我需要在文本视图中设置更多的阅读内容。所以我的方法是find适合文本视图的string范围,然后添加“See More”。是否有任何方法可以实现在Swift中。要求是模仿阅读更多的选项来显示完整的文本在像facebook这样的细节视图。

您正在寻找的function是CTFramesetterSuggestFrameSizeWithConstraints 。 本质上,它可以让你找出适合某一帧的字符数量。 您可以使用该号码来切断当前文本并插入一个button。

我为UILabel的子类写了一个这个函数的实现:

 - (NSInteger)numberOfCharactersThatFitLabel { // Create an 'CTFramesetterRef' from an attributed string CTFontRef fontRef = CTFontCreateWithName((CFStringRef)self.font.fontName, self.font.pointSize, NULL); NSDictionary *attributes = [NSDictionary dictionaryWithObject:(__bridge id)fontRef forKey:(id)kCTFontAttributeName]; CFRelease(fontRef); NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self.text attributes:attributes]; CTFramesetterRef frameSetterRef = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString); // Get a suggested character count that would fit the attributed string CFRange characterFitRange; CTFramesetterSuggestFrameSizeWithConstraints(frameSetterRef, CFRangeMake(0,0), NULL, CGSizeMake(self.bounds.size.width, self.numberOfLines*self.font.lineHeight), &characterFitRange); CFRelease(frameSetterRef); return (NSInteger)characterFitRange.length; } 

这是一个完整的实现将一个随机文本切割成指定数量的行并附加“查看更多”文本的沼泽岗位 。

这有点复杂,因为有些字母比其他字母宽。 但是你可以通过使用sizeWithAttributes方法来检查你的string的宽度:

 var yourString: String = textField.text let myString: NSString = originalString as NSString //Set your font and add attributes if needed. let stringSize: CGSize = myString.sizeWithAttributes([NSFontAttributeName: yourFont]) 

现在您收到一个CGSize,您可以检查宽度是否比您的文本字段宽。

 if(sizeOfYourTextfield < stringSize){ //String is too large for your UITextField } 

kgaidis的优秀答案粗略迅速的翻译。

 extension UILabel { func numberOfCharactersThatFitLabel() -> Int { let fontRef = CTFontCreateWithName(self.font.fontName as CFStringRef, self.font.pointSize, nil) let attributes = NSDictionary(dictionary: [kCTFontAttributeName : fontRef]) let attributeString = NSAttributedString(string: text!, attributes: attributes as? [String : AnyObject]) let frameSetterRef = CTFramesetterCreateWithAttributedString(attributeString as CFAttributedStringRef) var characterFitRange:CFRange CTFramesetterSuggestFrameSizeWithConstraints(frameSetterRef, CFRangeMake(0, 0), nil, CGSizeMake(bounds.size.width, CGFloat(numberOfLines)*font.lineHeight), &characterFitRange) return characterFitRange.length } }