MacOS 開發 — NSTextField的使用

以下記錄關於按鈕NSTextField在項目中涉及到的需求:

1、取消焦點的高亮狀態:

//點擊的時候不顯示藍色外框
self.focusRingType = NSFocusRingTypeNone; 

2、文字垂直居中:

- (NSRect)adjustedFrameToVerticallyCenterText:(NSRect)frame {
// super would normally draw text at the top of the cell
CGFloat fontSize = self.font.boundingRectForFont.size.height;
NSInteger offset = floor((NSHeight(frame) - ceilf(fontSize))/2)-5;
NSRect centeredRect = NSInsetRect(frame, 0, offset);
return centeredRect;
}
 - (void)editWithFrame:(NSRect)aRect inView:(NSView *)controlView
editor:(NSText *)editor delegate:(id)delegate event:(NSEvent *)event {
[super editWithFrame:[self adjustedFrameToVerticallyCenterText:aRect]
              inView:controlView editor:editor delegate:delegate event:event];
}
- (void)selectWithFrame:(NSRect)aRect inView:(NSView *)controlView
editor:(NSText *)editor delegate:(id)delegate
 start:(NSInteger)start length:(NSInteger)length {
[super selectWithFrame:[self adjustedFrameToVerticallyCenterText:aRect]
                inView:controlView editor:editor delegate:delegate
                 start:start length:length];
}
 - (void)drawInteriorWithFrame:(NSRect)frame inView:(NSView *)view {
[super drawInteriorWithFrame:
 [self adjustedFrameToVerticallyCenterText:frame] inView:view];
}

3、文字內容富文本顯示:

NSString *string = @"這是藍色文字,這是紅色文字。";
NSMutableAttributedString *colorTitle = [[NSMutableAttributedString alloc] initWithString: string];
[colorTitle addAttribute:NSForegroundColorAttributeName value:[NSColor blueColor] range:NSMakeRange(0, 7)];
[colorTitle addAttribute:NSForegroundColorAttributeName value:HEX_RGB_COLOR(0x38b162) range:NSMakeRange(7, 7)];
self.attributedStringValue = colorTitle;

4、改變邊框顏色:

self.bordered = YES;
self.wantsLayer = YES;
self.layer.borderColor = [NSColor redColor].CGColor;
self.layer.borderWidth = 1.0f;

// 一定要設置如下屬性,否則無法顯示效果

[[self cell] setBezeled:NO];
[[self cell] setBordered:NO];

5、多行文字換行:

整個窗體失去焦點,不閃爍光標: `[self.window makeFirstResponder:nil];`

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章