NSTextField と NSImageView を揃えようとしています。現在のコードは以下のとおりです。NSTextFieldCell のサブクラス化 (SO でここにあります)、テキスト フィールドのフレームのいじり、制約の微調整など、さまざまなアプローチを試しましたが、取得できません。下のスクリーンショットのように..
また、ラベルにフォントを適用しない場合、配置が期待どおりに機能することも発見しました。画像と垂直方向に配置されます。
したがって、問題は、a) 世界でフォントを適用すると位置合わせが台無しになる理由、および b) これを回避するにはどうすればよいか、理想的には実行時にフォントを変更した場合に適応する動的な方法で..
- (id)initWithFrame:(NSRect)frameRect {
self = [super initWithFrame:frameRect];
if (self) {
NSView *spacer1 = [[NSView alloc] init];
[spacer1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:spacer1];
NSView *spacer2 = [[NSView alloc] init];
[spacer2 setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:spacer2];
NSImage *icon = [NSImage imageNamed:@"05-arrow-west"];
NSImageView *iconView = [[NSImageView alloc] init];
[iconView setTranslatesAutoresizingMaskIntoConstraints:NO];
[iconView setImage:icon];
[self addSubview:iconView];
NSFont *font = [NSFont fontWithName:@"HelveticaNeue-Light" size:14];
NSTextField *label = [[NSTextField alloc] init];
[label setTranslatesAutoresizingMaskIntoConstraints:NO];
[label setEditable:NO];
[label setSelectable:NO];
[label setBezeled:NO];
[label setDrawsBackground:NO];
[label setFont:font];
[label setTextColor:[NSColor lightGrayColor]];
[label setStringValue:@"Test String"];
[self addSubview:label];
NSDictionary *views = NSDictionaryOfVariableBindings(iconView, label, spacer1, spacer2);
[self addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[spacer1(>=0)][iconView]-5-[label][spacer2(==spacer1)]|"
options: 0
metrics:nil
views:views]];
[self addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[iconView]|"
options: 0
metrics:nil
views:views]];
[self addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[label]|"
options: 0
metrics:nil
views:views]];
[self setContentHuggingPriority:200 forOrientation:NSLayoutConstraintOrientationVertical];
[iconView setContentHuggingPriority:200 forOrientation:NSLayoutConstraintOrientationVertical];
[label setContentHuggingPriority:200 forOrientation:NSLayoutConstraintOrientationVertical];
}
return self;
}