gpt4 book ai didi

iOS - 更改子类 UIView 的 subview 的框架(使用启用自动布局的 Storyboard)

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:03:13 28 4
gpt4 key购买 nike

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

我试过使用这些但没有成功:

[self updateConstraints];
[self layoutSubviews];

更新

我知道我需要设置一个约束以用于自动布局。但是,它需要以编程方式完成,因为我正在以这种方式创建子类 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];
}];

最佳答案

在使用自动布局时,切勿触摸框架。使用像这样的布局系统的全部意义在于,框架是根据附加到它们的可满足约束来推断的。

在不知道更多细节的情况下,解决这个问题的方法是创建从 Storyboard到相关 View 的 NSLayoutConstraint 导出。例如,您可能对进度 View 有宽度限制 - 创建一个 NSLayoutConstraint导出到宽度约束将允许您更新 constant,这反过来将调整框架。

动画示例:

self.widthConstraint.constant = 300;

[UIView animateWithDuration:0.4 animations:^{
[self.view layoutIfNeeded];
}];

2013 年 5 月 15 日更新

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

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

(抱歉格式化,这是一个很长的方法...)

然后添加NSArray的约束返回给父 View :

[self addConstraints:wc];

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

关于iOS - 更改子类 UIView 的 subview 的框架(使用启用自动布局的 Storyboard),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16515616/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com