Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Cocoa 对文本使用NSPopupButton的全宽,无箭头_Cocoa_Nspopupbutton - Fatal编程技术网

Cocoa 对文本使用NSPopupButton的全宽,无箭头

Cocoa 对文本使用NSPopupButton的全宽,无箭头,cocoa,nspopupbutton,Cocoa,Nspopupbutton,我喜欢显示一个没有箭头的nspoupbutton。我喜欢使用箭头用于标签文本的空间。默认情况下,这似乎不起作用 以下是启用箭头的文本(即“01234567890”): 这里没有箭头: 正如您所看到的,箭头将占据的空间不被文本使用 如何使用文本的完整内容宽度 我已经用F-Script检查了控件,但发现控件的子视图数组似乎是空的-我本来希望找到两个子视图,如果是这样,我会删除箭头的一个,并将文本的一个加宽。实现这一点的一种方法是创建一个nspoupbuttoncell子类,并在其drawTitl

我喜欢显示一个没有箭头的
nspoupbutton
。我喜欢使用箭头用于标签文本的空间。默认情况下,这似乎不起作用

以下是启用箭头的文本(即“01234567890”):

这里没有箭头:

正如您所看到的,箭头将占据的空间不被文本使用

如何使用文本的完整内容宽度


我已经用F-Script检查了控件,但发现控件的子视图数组似乎是空的-我本来希望找到两个子视图,如果是这样,我会删除箭头的一个,并将文本的一个加宽。

实现这一点的一种方法是创建一个
nspoupbuttoncell
子类,并在其
drawTitle:withFrame:inView:
方法中自己绘制文本

以下是它的精髓:

@interface MyCell : NSPopUpButtonCell
    @property NSDictionary<NSString*,id> *attrs;
@end

@implementation MyCell

-(NSRect)drawTitle:(NSAttributedString *)title withFrame:(NSRect)frame inView:(NSView *)controlView
{
    CGSize cs = controlView.bounds.size;
    CGPoint or = frame.origin;
    CGSize fs = frame.size;
    const int th = fs.height;
    const int inset = th * 2 / 3;
    const int indent = self.image ? th+6 : 0; // assuming the img is on the left of the text, we'll indent the text
    frame = CGRectMake (inset+indent, or.y, cs.width-2*inset-indent, fs.height);
    return [super drawTitle:title withFrame:frame inView:controlView];
}

@end
接口MyCell:NSPopUpButtonCell @属性NSDictionary*attrs; @结束 @实现迈塞尔 -(NSRect)drawTitle:(NSAttributedString*)带边框的标题:(NSRect)查看中的边框:(NSView*)控制视图 { CGSize cs=controlView.bounds.size; CGPoint或=frame.origin; CGSize fs=frame.size; const int th=fs.高度; 常数int inset=th*2/3; const int indent=self.image?th+6:0;//假设img位于文本的左侧,我们将缩进文本 框架=CGRectMake(插入+缩进,或.y,cs.宽度-2*插入缩进,fs.高度); 返回[super drawTitle:title with frame:frame inView:controlView]; } @结束 注意:这段代码并没有涵盖所有可能在菜单项中添加图标的情况-它只处理最常见的在左边有一个配件图标的情况,这仍然有点不可靠,因为使用了我通过反复试验发现的缩进值。根据需要自行调整

另请参见下面@NSGod关于在nib或故事板中设置单元格类的评论

更新:优化了代码,只需要
nspoupbuttoncell
的子类,而不需要
nspoupbutton
的子类,这要感谢@NSGod


更新2:而不是实现
drawTitleWithFrame:inView:
我现在覆盖
drawTitle:withFrame:inView:
,因为这为我提供了正确居中的绘图框架,并使整个代码更短。

您应该能够在nib文件。选择nib文件中的
nspoupButton
,然后再次单击以选择单元格(使用左侧的nib层次结构大纲视图验证是否选中了单元格)。在Identity inspector中,将自定义类设置为
MyCell
。然后,您可以设置单元格的所有属性,并应保留这些属性。当nib加载时,这将调用
MyCell
initWithCoder:
方法,因此,如果您已经覆盖了它,请确保在任何自定义之前调用
[super initWithCoder:coder]
。@NSGod我以前从未注意到第二次单击会选择单元格,尽管我注意到发生了一些变化。现在唯一需要解决的问题是将文本垂直居中,尽管这应该很容易。理论上。