【发布时间】:2010-10-25 00:39:51
【问题描述】:
使用界面生成器,您可以选择对象在调整大小时应坚持的角。你怎么能以编程方式做到这一点?
【问题讨论】:
-
请注意,Apple 为 Lion 引入了 AutoLayout framework。
标签: objective-c cocoa macos
使用界面生成器,您可以选择对象在调整大小时应坚持的角。你怎么能以编程方式做到这一点?
【问题讨论】:
标签: objective-c cocoa macos
参见 NSView 的setAutoresizingMask: 方法和相关的resizing masks。
【讨论】:
每个视图都有标志掩码,通过设置 autoresizingMask 属性与您想要从resizing masks 获得的行为的 OR 来控制。另外superview需要配置为resize its subviews。
最后,除了基本的掩码定义的调整大小选项外,您还可以通过实现-resizeSubviewsWithOldSize:来完全控制子视图的布局
【讨论】:
我发现 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];
【讨论】:
@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]; }
来自可可文档:
NSViewMinYMargin
The bottom margin between the receiver and its superview is flexible. Available in OS X v10.0 and later.
【讨论】: