[英]NSParagraphStyle is changed when resigning UITextField's first responder
I have a UITextField
in a custom UITableViewCell
whose text I would like to truncate from the head, not the tail. 我在自定义
UITableViewCell
有一个UITextField
,其文本我想从头部而不是尾部截断。
I am setting the line break mode in awakeFromNib
: 我在
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;
}
While it gets set, leaving the text field (resigning the first responder) seems to cause the NSLineBreakByTruncatingTrail
to be used instead. 设置
NSLineBreakByTruncatingTrail
后,离开文本字段(退出第一个响应者)似乎会导致使用NSLineBreakByTruncatingTrail
代替。
The change happens somewhere between textFieldShouldEndEditing:
and textFieldDidEndEditing:
: When I set breakpoints in both methods, the line break mode in the first is NSLineBreakByTruncatingHead
but NSLineBreakByTruncatingTail
by the second. 变化发生介于
textFieldShouldEndEditing:
和textFieldDidEndEditing:
当我在这两种方法中设置断点,在第一行中断模式是NSLineBreakByTruncatingHead
但NSLineBreakByTruncatingTail
第二。
Is there a way that I can set the line break mode and have it stick? 有没有一种方法可以设置换行模式并使其停留?
I know, this question is not new, but I'm struggling with that problem since hours and the only way I found it working at the end was the following (hope it helps other people struggling with that problem). 我知道,这个问题并不是新问题,但是由于数小时以来我一直在苦苦挣扎,而我最终发现它起作用的唯一方法是以下方法(希望它可以帮助其他苦苦挣扎于此问题的人)。
Override the drawTextInRect
method of UITextField
and set the defaultTextAttributes
elsewhere in code (I did it in init
method in my custom UITextField
subclass): 重写
UITextField
的drawTextInRect
方法,并在代码中的其他位置设置defaultTextAttributes
(我在自定义UITextField
子类的init
方法中进行了设置):
- (void) drawTextInRect : (CGRect) rect {
[[self text] drawInRect: rect withAttributes: self.defaultTextAttributes];
}
... and elsewhere in code: ...以及代码中的其他地方:
// 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.