MAC开发--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];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容