【问题标题】:NSParagraphStyle is changed when resigning UITextField's first responder辞职 UITextField 的第一响应者时更改 NSParagraphStyle
【发布时间】:2013-11-26 12:46:54
【问题描述】:

我在自定义 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

有没有办法可以设置换行模式并让它坚持下去?

【问题讨论】:

    标签: ios objective-c uikit uitextfield nsattributedstring


    【解决方案1】:

    我知道,这个问题并不新鲜,但我从几个小时以来一直在努力解决这个问题,我发现它最后工作的唯一方法是以下(希望它可以帮助其他人解决这个问题)。

    覆盖UITextFielddrawTextInRect 方法并在代码中的其他位置设置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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多