Autolayout constraints do no work for NSView composition with drawRect:

淺唱寂寞╮ 提交于 2019-12-02 02:26:02

问题


I am trying to apply Autolayout constraints to a custom button which inherits from NSView. The button is rather complex and can be used as radio button for example. The user interface is composed in drawRect: as you can guess from the following code excerpt.

@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];
    }
}

I successfully configured a custom text field which derives from NSView. The difference is that the text field uses addSubView: to compose its user interface components.

I wonder if it still possible to use Autolayout constraints to position the user interface components. In the moment no component shows up. I have the feeling that it does not work because I draw those "subviews".


回答1:


I managed to solve the problem by implementing the intrinsicContentSize in CustomButton.

#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);
}


来源:https://stackoverflow.com/questions/13029052/autolayout-constraints-do-no-work-for-nsview-composition-with-drawrect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!