我在自定义 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
(我在 init
我的自定义 UITextField
子类中的方法):
- (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;
关于ios - 辞去 UITextField 的第一响应者时,NSParagraphStyle 发生了变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20217505/