我正在尝试申请Autolayout对继承自 NSView
的自定义按钮的约束。该按钮相当复杂,例如可以用作单选按钮。用户界面由 drawRect:
组成,您可以从以下代码摘录中猜到。
@interface CustomButton : NSView
...
- (void)drawRect:(NSRect)dirtyRect {
// ...
if (self.hasImage) {
// ...
if (self.hasTitle) {
// ...
[image drawInRect:imgRect
fromRect:NSZeroRect
operation:NSCompositeSourceOver
fraction:fraction
alignment:Alignment_LEFT];
} else {
[image drawInRect:imgRect
fromRect:NSZeroRect
operation:NSCompositeSourceOver
fraction:fraction
alignment:Alignment_CENTER];
}
}
if (self.hasTitle) {
// ...
[self.textRenderer drawText:m_title
inRect:textRect
withState:state
controlView:self];
}
}
我成功配置了一个派生自 NSView 的自定义文本字段。不同之处在于文本字段使用 addSubView:
来组成其用户界面组件。
我想知道是否仍然可以使用自动布局约束来定位用户界面组件。目前没有任何组件出现。我感觉它不起作用,因为我绘制了那些“ subview ”。
最佳答案
我通过在 CustomButton
中实现 intrinsicContentSize
成功解决了该问题。
#pragma mark - NSConstraintBasedLayoutFittingSize
/**
Returns a suitable size for the receiver.
This settings may not apply if a layout constraint
defines minimum values for the width or height of the element.
@returns A size for the receiver.
*/
- (NSSize)intrinsicContentSize {
// Calculation of width and height of the rendered text.
return NSMakeSize(width, height);
}
关于cocoa - 自动布局约束对于带有drawRect :的NSView合成不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13029052/