[英]Remove IBOutlet programmatically that is set in interface builder and add it again with same constraints
[英]iOS: programmatically changing constraints set from Interface Builder
美好的一天,朋友們!
我沒有嘗試動畫從代碼中設置在IB中的視圖。 應用崩潰的原因如下:
視圖層次結構沒有為約束准備......
我在這里看到了一些類似的問題,原因始終是以編程方式創建的視圖尚未添加到superview中。 但我在IB中創建了所有觀點!
控制台還說:
在容器層次結構中找不到視圖:( 這里是超級視圖)
它對我沒有任何意義,因為事實上它是適當的superview的子視圖,xcode知道它 - 它立即打印視圖層次結構,它適合。
可能是什么原因? 謝謝!
編輯:我使用的代碼:
- (void)setEditingConstraintsForView:(UIView *)view
{
// Pin given view to top, fix it height
NSDictionary *givenView = @{@"view":view};
view.translatesAutoresizingMaskIntoConstraints = NO;
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil views:givenView];
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view(height)]" options:0 metrics:@{@"height":@(viewHeight)} views:givenView];
[self.animatedVIew addSubview:view];
for (NSArray *constraints in @[horizontalConstraints, verticalConstraints]) {
[view addConstraints:constraints];
}
}
我還刪除了在安裝new之前在IB中設置的所有約束:
- (NSDictionary *)constraintsFromIB
{
if (!_constraintsFromIB) {
_constraintsFromIB = @{@"view1":self.view1.referencingConstraintsInSuperviews,
@"view2":self.view2.referencingConstraintsInSuperviews,
@"view3":self.view3.referencingConstraintsInSuperviews };
}
return _constraintsFromIB;
}
然后:
- (void)updateViewConstraints
{
[super updateViewConstraints];
// clear all constraints
for (NSString *viewName in self.constraintsFromIB.allKeys) {
for (NSLayoutConstraint *constraint in self.constraintsFromIB[viewName]) {
[constraint remove];
}
}}
更新2:方法我使用調用更改:當用戶觸摸視圖時,調用此視圖:
- (void)animateConstraintsForState:(LDYEditingLabel)state
{
self.editingLabel = state;
[UIView animateWithDuration:0.3 animations:^{
[self updateViewConstraints];
[self.view layoutIfNeeded];
}];
}
稍后在updateViewConstraints:
有一個代碼觸發我的方法setEditingConstraintsForView:(UIView *)view
如果您使用IB創建約束,則可以添加約束作為插座。
然后更新約束並調用[self updateViewConstraints]; 在動畫塊中
如果是我,我會將約束連接到IBOutlets,只修改現有的約束。 它可能最終比以編程方式添加和刪除它們更容易。
修改約束后,您可能還需要調用setNeedsLayout
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.