我在一个自定义UITableViewCell
中有一个UITextField
,我想从头部而不是尾部截断它的文本。
我正在awakeFromNib
:中设置断线模式
- (void)awakeFromNib
{
[super awakeFromNib];
NSMutableDictionary* textAttributes = [self.textField.defaultTextAttributes mutableCopy];
NSMutableParagraphStyle* paragraphStyle = [self.textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingHead;
[textAttributes setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
[textAttributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
self.textField.defaultTextAttributes = textAttributes;
}
当它被设置时,留下文本字段(放弃第一个响应程序)似乎会导致使用NSLineBreakByTruncatingTrail
。
这种变化发生在textFieldShouldEndEditing:
和textFieldDidEndEditing:
之间:当我在两种方法中设置断点时,第一种方法中的换行模式是NSLineBreakByTruncatingHead
,但第二种方法中是NSLineBreakByTruncatingTail
。
有没有一种方法可以设置换行模式并使其保持不变?
我知道,这个问题并不是什么新鲜事,但我从几个小时以来就一直在努力解决这个问题,最后我发现它唯一有效的方法是以下方法(希望它能帮助其他解决这个问题的人)。
重写UITextField
的drawTextInRect
方法,并在代码中的其他地方设置defaultTextAttributes
(我在自定义UITextField
子类的init
方法中进行了此操作):
- (void) drawTextInRect : (CGRect) rect {
[[self text] drawInRect: rect withAttributes: self.defaultTextAttributes];
}
以及代码中的其他部分:
// get defaultTextAttributes of the TextField
NSMutableDictionary* textAttributes = [self.defaultTextAttributes mutableCopy];
// get default paragraph style from the defaultTextAttributes
NSMutableParagraphStyle* paragraphStyle = [textAttributes[NSParagraphStyleAttributeName] mutableCopy];
// change the lineBreakMode as desired
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingHead;
// put changed paragraphStyle into textAttributes
[textAttributes setObject: paragraphStyle forKey: NSParagraphStyleAttributeName];
// set the defaultTextAttributes of the textField
self.defaultTextAttributes = textAttributes;