【发布时间】:2015-03-20 13:42:28
【问题描述】:
我创建了一个自定义的 IB 可设计视图(参见下面的代码),它可以在 IB 中正确呈现,并且在运行时也可以正常工作。但是,在收到有关视图放错位置的警告时,我无法在 Interface Builder 中手动调整视图的大小(当触摸调整大小手柄时,视图将在其容器中跳转)。
对于各种不同的布局,我得到相同或相似的行为。如果我在这里做错了什么,或者这只是 IB 中的一个错误,你知道吗?
(PS:我不能忽略警告)
编辑:添加约束截图:
这是代码(标题):
IB_DESIGNABLE
@interface AKATestView : UIView
@end
实施:
@interface AKATestView()
@property(nonatomic)BOOL subviewsCreated;
@property(nonatomic)BOOL subviewConstraintsCreated;
@property(nonatomic)NSDictionary* views;
@end
@implementation AKATestView
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[self setupAfterInit];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setupAfterInit];
}
return self;
}
- (void)setupAfterInit
{
[self createSubviews];
}
- (void)createSubviews
{
if (!self.subviewsCreated)
{
self.translatesAutoresizingMaskIntoConstraints = NO;
UILabel* labelView = [[UILabel alloc] initWithFrame:CGRectZero];
labelView.text = @"Name";
labelView.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:labelView];
UITextField* textField = [[UITextField alloc] initWithFrame:CGRectZero];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.placeholder = @"Enter some text";
textField.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:textField];
UILabel* errorMessageLabel = [[UILabel alloc] initWithFrame:CGRectZero];
errorMessageLabel.text = @"Error message";
errorMessageLabel.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:errorMessageLabel];
self.views = @{ @"label": labelView, @"editor": textField, @"errorMessageLabel": errorMessageLabel };
self.subviewsCreated = YES;
[self setNeedsUpdateConstraints];
}
}
- (void)updateConstraints
{
if (!self.subviewConstraintsCreated)
{
NSDictionary* metrics =
@{ @"pt": @(4), @"pr": @(4), @"pb": @(4), @"pl": @(4),
@"labelWidth": @(100),
@"errorPl": @(4 + 100 + 4),
@"hsLabelEditor": @(4), @"vsEditorError": @(2)
};
NSArray* specs =
@[ @{ @"format": @"H:|-(pl)-[label(labelWidth)]-(hsLabelEditor)-[editor]-(pr)-|",
@"options": @(NSLayoutFormatAlignAllFirstBaseline) },
@{ @"format": @"V:|-(pt)-[editor]-(vsEditorError)-[errorMessageLabel]-(pb)-|",
@"options": @(NSLayoutFormatAlignAllLeading|NSLayoutFormatAlignAllTrailing) }
];
for (NSDictionary* spec in specs)
{
NSString* format = spec[@"format"];
NSUInteger options = ((NSNumber*)spec[@"options"]).unsignedIntegerValue;
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:format
options:options
metrics:metrics
views:self.views];
[self addConstraints:constraints];
}
self.subviewConstraintsCreated = YES;
}
[super updateConstraints];
}
@end
【问题讨论】:
-
当心你的约束和弹簧。该实施与 IMO 问题无关,请包括约束而不是它。
-
添加了一个带有约束的屏幕截图,这就是你要找的@Bigood?
-
Storyboard 不查看代码中设置的约束。只有您在情节提要中指定的那些。
-
IB 可能不会查看从代码 (?) 设置的约束,但只要根据内部约束正确计算视图的高度,这些约束就会影响 IB。视图也正确呈现。我认为您忽略了视图正在使用实时渲染(参见 IB_DESIGNABLE)。
-
我遇到了同样的问题。如果我找到任何解决方案,我会通知您。
标签: ios xcode6 autolayout ibdesignable