Cocoa NSView更改自动调整属性

Ben*_*ves 21 macos cocoa objective-c

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

Interface Builder

e.J*_*mes 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
Run Code Online (Sandbox Code Playgroud)


// 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
Run Code Online (Sandbox Code Playgroud)

然后可以使用如下:

[someView fixLeftEdge:YES];
[someView fixTopEdge:YES];
[someView fixWidth:NO];
Run Code Online (Sandbox Code Playgroud)

  • 其实,是.我一直致力于触摸屏界面的自定义UI,而Interface Builder根本不适合这项工作.我一直在做代码中的一切,我没有回头. (8认同)
  • 所以你的意思是当你在调整大小时告诉视图该做什么时,你可以知道你在做什么吗?如果有一个诺贝尔和平奖编码,你有我的投票. (2认同)

Mar*_*don 19

请参阅NSView 的setAutoresizingMask:方法和相关的大小调整掩码.


tjw*_*tjw 8

每个视图都有标志掩码,通过使用调整大小掩码所需行为的OR设置autoresizingMask属性来控制.此外,需要配置superview以调整其子视图的大小.

最后,除了基本的蒙版定义的大小调整选项之外,您还可以通过实现-resizeSubviewsWithOldSize来完全控制子视图的布局: