Cocoa 自动布局约束不适用于使用drawRect的NSView合成:

Cocoa 自动布局约束不适用于使用drawRect的NSView合成:,cocoa,nsview,drawrect,autolayout,Cocoa,Nsview,Drawrect,Autolayout,我试图将约束应用于从NSView继承的自定义按钮。按钮相当复杂,例如可以用作单选按钮。用户界面由drawRect:组成,您可以从以下代码摘录中猜到 @interface CustomButton : NSView 我成功配置了从NSView派生的自定义文本字段。不同之处在于,文本字段使用addSubView:组成其用户界面组件 我想知道是否仍然可以使用自动布局约束来定位用户界面组件。在那一刻,没有任何组件出现。我感觉它不起作用,因为我绘制了那些“子视图”。我通过在自定义按钮中实现intrin

我试图将约束应用于从
NSView
继承的自定义按钮。按钮相当复杂,例如可以用作单选按钮。用户界面由
drawRect:
组成,您可以从以下代码摘录中猜到

@interface CustomButton : NSView

我成功配置了从NSView派生的自定义文本字段。不同之处在于,文本字段使用
addSubView:
组成其用户界面组件


我想知道是否仍然可以使用自动布局约束来定位用户界面组件。在那一刻,没有任何组件出现。我感觉它不起作用,因为我绘制了那些“子视图”。

我通过在
自定义按钮中实现
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);
}
#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);
}