iOS - 更改子类UIView的子视图的框架(使用启用了自动布局的故事板)

Jim*_*med 2 frame subview storyboard uiview ios

我正在构建一个自定义进度条(UIView的子类).我向UIView添加了一个UIImageView,它使用重复的图像来显示进度.视图被添加到故事板中,我可以让它显示得很好,但是如果我尝试更改框架,那么它只显示故事板文件中显示的内容(即,如果故事板视图具有黄色背景,但代码uiview子类将其更改为绿色,如果我尝试在代码中更改UIImageView的框架以反映当前进度,则默认返回黄色背景)

我尝试使用这些没有运气:

[self updateConstraints];
[self layoutSubviews];
Run Code Online (Sandbox Code Playgroud)

UPDATE

我知道我需要设置一个约束用于autolayout.但是,它需要以编程方式完成,因为我正在以这种方式创建子类UIView.这是我正在尝试的代码,我知道我很接近,但不能让它工作:

[self addConstraint:
 [NSLayoutConstraint constraintWithItem:self.progressView
                              attribute:NSLayoutAttributeWidth
                              relatedBy:NSLayoutRelationLessThanOrEqual
                                 toItem:nil
                              attribute:NSLayoutAttributeWidth
                             multiplier:1
                               constant:progressWidth]];

[UIView animateWithDuration:3 animations:^{
    [self.progressView layoutIfNeeded];
}];
Run Code Online (Sandbox Code Playgroud)

Dan*_*izl 7

当使用自动布局一个工作应该永远不会碰框架.使用这样的布局系统的全部意义在于,帧是基于附加到它们的可满足约束来推断的.

在不知道更多细节的情况下,解决这个问题的方法是从故事板创建NSLayoutConstraint出口到相关视图.例如,您可能在进度视图上有宽度约束 - 创建宽度约束的NSLayoutConstraint出口将允许您更新constant,然后将调整框架.

动画示例:

self.widthConstraint.constant = 300;

[UIView animateWithDuration:0.4 animations:^{
    [self.view layoutIfNeeded];
}];
Run Code Online (Sandbox Code Playgroud)

2013年5月15日更新

下面是使用约束的可视化格式以编程方式创建约束的示例(更易于使用)

UIView *w_progressView = self.progressView
NSArray *wc = [NSLayoutConstraint constraintsWithVisualFormat:@"[w_progressView(200)]"
                                                                              options:0
                                                                              metrics:nil
                                                                                views:NSDictionaryOfVariableBindings(w_progressView)];
Run Code Online (Sandbox Code Playgroud)

(对不起格式化,这是一个很长的方法...)

然后添加返回到父视图的约束的NSArray:

[self addConstraints:wc];
Run Code Online (Sandbox Code Playgroud)

符号progressView(200)在视图progressView上放置200点宽度