使用Cocoa自动布局在自定义视图中填充内容 [英] Content padding in custom view with Cocoa auto layout

查看:48
本文介绍了使用Cocoa自动布局在自定义视图中填充内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的NSView子类,该子类周围有边框.在此视图内部绘制边框.可以通过自动布局来尊重这一边界吗?

I have a custom NSView subclass which has a border around itself. The border is drawn inside this view. Is it possible to respect this borders with auto layout?

例如,当我将子视图放置到自定义视图并设置约束时,如下所示:

For example, when I place the subview to my custom view and set constraints like this:

@"H:|-(myViewSubView)-|" (not @"H:|-(myViewBorderWidth)-(myViewSubView)-(myViewBorderWidth)-|")
@"V:|-(myViewSubView)-|"

布局必须为:

Horizontal: |-(myViewBorderWidth)-|myViewSubview|-(myViewBorderWidth)-|
  Vertical: |-(myViewBorderWidth)-|myViewSubview|-(myViewBorderWidth)-| 

我尝试覆盖视图中的-bounds方法以返回无边界的rect矩形,但这无济于事.

I've tried to overwrite -bounds method in my view to return the bounds rect without the borders, but it doesn't help.

推荐答案

我发现的一个解决方案是重载addConstraint:方法并在添加约束之前对其进行修改:

The one solution I found is to overload the addConstraint: method and modify constraints before they'll be added:

- (void)addConstraint:(NSLayoutConstraint *)constraint
{
    if(constraint.firstItem == self || constraint.secondItem == self) {
        if(constraint.firstAttribute == NSLayoutAttributeLeading) {
            constraint.constant += self.leftBorderWidth;
        } else if (constraint.firstAttribute == NSLayoutAttributeTrailing) {
            constraint.constant += self.rightBorderWidth;
        } else if (constraint.firstAttribute == NSLayoutAttributeTop) {
            constraint.constant += self.topBorderWidth;
        } else if (constraint.firstAttribute == NSLayoutAttributeBottom) {
            constraint.constant += self.bottomBorderWidth;
        }
    }

    [super addConstraint:constraint];
}

然后还要在xxxBorderWidth设置器中处理此约束.

And then also handle this constraints in xxxBorderWidth setters.

这篇关于使用Cocoa自动布局在自定义视图中填充内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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