自动布局约束对带有 drawRect 的 NSView 组合不起作用: [英] Autolayout constraints do no work for NSView composition with drawRect:

查看:32
本文介绍了自动布局约束对带有 drawRect 的 NSView 组合不起作用:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试申请 Autolayout 约束从 NSView 继承的自定义按钮.该按钮相当复杂,例如可以用作单选按钮.用户界面由 drawRect: 组成,您可以从以下代码摘录中猜到.

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

我成功配置了一个源自 NSView 的自定义文本字段.不同之处在于文本字段使用 addSubView: 来组成其用户界面组件.

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.

我想知道是否仍然可以使用 Autolayout 约束来定位用户界面组件.目前没有组件出现.我感觉它不起作用,因为我画了那些子视图".

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".

推荐答案

我设法通过在 CustomButton 中实现 intrinsicContentSize 解决了这个问题.

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

这篇关于自动布局约束对带有 drawRect 的 NSView 组合不起作用:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆