Search code examples
cocoanstextfieldcellfieldeditor

Text attribute changed for NSTextFieldCell on selection


I have a tableview on which selecting a column of a row will call overridden method

- (void)selectWithFrame:(NSRect)inCellFrame inView:(NSView *)inControlView editor:(NSText *)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength {
  // here do some text positioning
         [super selectWithFrame:inCellFrame inView:inControlView editor:textObj delegate:anObject start:selStart length:selLength];
}

I also return field editor for the cell as under:

- (NSTextView *)fieldEditorForView:(NSView *)inControlView {
   MYTextView* fieldEditor = [[[MYTextView alloc] initWithFrame:NSZeroRect] autorelease];
   return fieldEditor;
}

When the cell is selected the text within the cell changes its attribute. Like, the font size, font face, font style, etc changes accordingly, seems I have no control over it when the text is in selection mode. I do not want to change the font properties thereof even after selection How can i avoid this changes in text attributes?


Solution

  • After calling -[super selectWithFrame:...] method, changes to the text properties will be reflected. The solution is below:

    - (void)selectWithFrame:(NSRect)inCellFrame
                     inView:(NSView *)inControlView
                     editor:(NSText *)textObj
                   delegate:(id)anObject
                      start:(NSInteger)selStart
                     length:(NSInteger)selLength {
        // here do some text positioning
    
        [super selectWithFrame:inCellFrame
                        inView:inControlView
                        editor:textObj
                      delegate:anObject
                         start:selStart
                        length:selLength];
    
        NSMutableAttributedString* text = [textObj textStorage];
    
        NSMutableParagraphStyle *alignmentStyle = [[NSParagraphStyle defaultParagraphStyle] autorelease];
        [alignmentStyle setAlignment:NSLeftTextAlignment];
    
        NSDictionary* attributes = [NSMutableDictionary dictionary];
        [attributes setValue:[NSFont boldSystemFontOfSize:[NSFont systemFontSize]] forKey:NSFontAttributeName];
        [attributes setValue:leftAlignmentStyle forKey:NSParagraphStyleAttributeName];
    
        [text setAttributes:attributes range:NSMakeRange(0, [text length])];
    }