MacOS 开发 — NSTextField的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HeroGuo_JP/article/details/88674064

以下记录关于按钮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];`

猜你喜欢

转载自blog.csdn.net/HeroGuo_JP/article/details/88674064