Cocoa NSView更改自动调整属性

时间:2009-05-09 17:15:57

标签: objective-c cocoa macos

使用界面构建器,您可以选择对象在调整大小时应该坚持的角落。你怎么能以编程方式做到这一点?

Interface Builder

4 个答案:

答案 0 :(得分:30)

我发现autoresizingBit掩码的命名非常可怕,所以我在NSView上使用了一个类别来使事情变得更加明确:

// MyNSViewCategory.h:
@interface NSView (myCustomMethods)

- (void)fixLeftEdge:(BOOL)fixed;
- (void)fixRightEdge:(BOOL)fixed;
- (void)fixTopEdge:(BOOL)fixed;
- (void)fixBottomEdge:(BOOL)fixed;
- (void)fixWidth:(BOOL)fixed;
- (void)fixHeight:(BOOL)fixed;

@end


// MyNSViewCategory.m:
@implementation NSView (myCustomMethods)

- (void)setAutoresizingBit:(unsigned int)bitMask toValue:(BOOL)set
{
    if (set)
    { [self setAutoresizingMask:([self autoresizingMask] | bitMask)]; }
    else
    { [self setAutoresizingMask:([self autoresizingMask] & ~bitMask)]; }
}

- (void)fixLeftEdge:(BOOL)fixed
{ [self setAutoresizingBit:NSViewMinXMargin toValue:!fixed]; }

- (void)fixRightEdge:(BOOL)fixed
{ [self setAutoresizingBit:NSViewMaxXMargin toValue:!fixed]; }

- (void)fixTopEdge:(BOOL)fixed
{ [self setAutoresizingBit:NSViewMinYMargin toValue:!fixed]; }

- (void)fixBottomEdge:(BOOL)fixed
{ [self setAutoresizingBit:NSViewMaxYMargin toValue:!fixed]; }

- (void)fixWidth:(BOOL)fixed
{ [self setAutoresizingBit:NSViewWidthSizable toValue:!fixed]; }

- (void)fixHeight:(BOOL)fixed
{ [self setAutoresizingBit:NSViewHeightSizable toValue:!fixed]; }

@end

然后可以按如下方式使用:

[someView fixLeftEdge:YES];
[someView fixTopEdge:YES];
[someView fixWidth:NO];

答案 1 :(得分:19)

请参阅NSView的setAutoresizingMask:方法和相关的resizing masks

答案 2 :(得分:8)

每个视图都有标志的掩码,通过使用resizing masks中所需行为的OR设置autoresizingMask属性来控制。此外,superview需要配置为resize its subviews

最后,除了基本的蒙版定义的大小调整选项之外,您还可以通过实施-resizeSubviewsWithOldSize:

来完全控制子视图的布局

答案 3 :(得分:3)

@ e.James回答给了我一个想法,只需创建一个更熟悉命名的新枚举:

typedef NS_OPTIONS(NSUInteger, NSViewAutoresizing) {
    NSViewAutoresizingNone                 = NSViewNotSizable,
    NSViewAutoresizingFlexibleLeftMargin   = NSViewMinXMargin,
    NSViewAutoresizingFlexibleWidth        = NSViewWidthSizable,
    NSViewAutoresizingFlexibleRightMargin  = NSViewMaxXMargin,
    NSViewAutoresizingFlexibleTopMargin    = NSViewMaxYMargin,
    NSViewAutoresizingFlexibleHeight       = NSViewHeightSizable,
    NSViewAutoresizingFlexibleBottomMargin = NSViewMinYMargin
};

另外,根据我的研究,我发现@ James.s在NSView添加中有一个严重错误。 Cocoa中的坐标系统在iOS坐标系统中有一个翻转的y轴。因此,为了修复底部和顶部边距,您应该写:

- (void)fixTopEdge:(BOOL)fixed
{ [self setAutoresizingBit:NSViewMaxYMargin toValue:!fixed]; }

- (void)fixBottomEdge:(BOOL)fixed
{ [self setAutoresizingBit:NSViewMinYMargin toValue:!fixed]; }

来自cocoa docs:

  

NSViewMinYMargin

The bottom margin between the receiver and its superview is flexible.
Available in OS X v10.0 and later.