ios - 辞去 UITextField 的第一响应者时,NSParagraphStyle 发生了变化

标签 ios objective-c uikit uitextfield nsattributedstring

我在自定义 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: 之间:当我在这两种方法中设置断点时,第一个中的换行模式是 NSLineBreakByTruncatingHeadNSLineBreakByTruncatingTail 是第二个。

有没有办法可以设置换行模式并让它保持不变?

最佳答案

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

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

相关文章:

ios - Swift:选择搜索结果后返回tableview

ios - iOS 7中的Spotlight TableView是怎么做出来的?

ios - 如何在中心显示具有自定义大小的模态视图 Controller ?

iOS 推送通知 - 检查应用程序在后台时是否显示横幅

iphone - View Controller 不会自动旋转到纵向倒置

IOS/objective-c : code reduction within animations

objective-c - 在类方法错误中访问实例变量 'variable'

ios - UICollectionView.scrollToItemAtIndexPath 动画与虚拟键盘一起工作很奇怪

ios - 如何在odoo中创建客户(res.partner)时添加标签(Category_id)?

objective-c - 具有多个管道输入的 NSTask