简体   繁体   中英

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.

I am setting the line break mode in 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.

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.

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):

- (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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM