如何实现像NSLineBreakByTruncatingHead为UITextField?

我需要为UITextField完全类似NSLineBreakByTruncatingHead ,如下所示。 我们假设原文是:

这是在UITextField中不能显示的长文本

我需要它像:

…不能显示在UITextField中

但目前我正在得到像这样的东西:

这是很长的文字,不能…

简单地说是在开始时的截断。 未给出UITextFieldlineBreakMode属性。 我怎样才能做到这一点?

我在这里采取的解决scheme,并修改它截断一个string,而不是尾巴的头。 知道它只显示字段不被编辑时的省略号。

注意:此解决scheme仅适用于iOS 7+。 要在iOS 6中使用,请在NSString + TruncateToWidth.m文件中使用sizeWithFont:而不是sizeWithAttributes:
编辑:增加了对iOS 6的支持

的NSString + TruncateToWidth.h

 @interface NSString (TruncateToWidth) - (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font; @end 

的NSString + TruncateToWidth.m

 #import "NSString+TruncateToWidth.h" #define ellipsis @"…" @implementation NSString (TruncateToWidth) - (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font { // Create copy that will be the returned result NSMutableString *truncatedString = [self mutableCopy]; // Make sure string is longer than requested width if ([self widthWithFont:font] > width) { // Accommodate for ellipsis we'll tack on the beginning width -= [ellipsis widthWithFont:font]; // Get range for first character in string NSRange range = {0, 1}; // Loop, deleting characters until string fits within width while ([truncatedString widthWithFont:font] > width) { // Delete character at beginning [truncatedString deleteCharactersInRange:range]; } // Append ellipsis [truncatedString replaceCharactersInRange:NSMakeRange(0, 0) withString:ellipsis]; } return truncatedString; } - (CGFloat)widthWithFont:(UIFont *)font { if([self respondsToSelector:@selector(sizeWithAttributes:)]) return [self sizeWithAttributes:@{NSFontAttributeName:font}].width; return [self sizeWithFont:font].width; } 

使用它:

 ... // Make sure to import the header file where you want to use it // assumes instance variable holds your string that populates the field fieldString = @"abcdefghijklmnopqrstuvwxyz1234567890"; // Size will need to be less than text field's width to account for padding _myTextField.text = [fieldString stringByTruncatingToWidth:(_myTextField.frame.size.width - 15) withFont:_myTextField.font]; ... // use textFieldShouldBeginEditing to make it animate from the start of the field to the end of the string if you prefer that. I found it a little distracting - (void)textFieldDidBeginEditing:(UITextField *)textField { textField.text = fieldString; } - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { fieldString = textField.text; textField.text = [textField.text stringByTruncatingToWidth:(textField.frame.size.width - 15) withFont:textField.font]; return YES; }