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];`

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值