Fis*_*cle 36 iphone resize uibutton uiview ios
当我向a添加子视图UIView时,或者当我调整现有子视图的大小时,我希望[view sizeToFit]并[view sizeThatFits]反映出这种变化.但是,我的经验是sizeToFit什么都不做,并sizeThatFits在更改之前和之后返回相同的值.
我的测试项目有一个包含单个按钮的视图.单击该按钮会向视图添加另一个按钮,然后调用sizeToFit包含视图.在添加子视图之前和之后,视图的边界将转储到控制台.
- (void) logSizes {
NSLog(@"theView.bounds: %@", NSStringFromCGRect(theView.bounds));
NSLog(@"theView.sizeThatFits: %@", NSStringFromCGSize([theView sizeThatFits:CGSizeZero]));
}
- (void) buttonTouched {
[self logSizes];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(10.0f, 100.0f, 400.0f, 600.0f);
[theView addSubview:btn];
[theView sizeToFit];
[self performSelector:@selector(logSizes) withObject:nil afterDelay:1.0];
}
Run Code Online (Sandbox Code Playgroud)
输出是:
2010-10-15 15:40:42.359 SizeToFit[14953:207] theView.bounds: {{0, 0}, {322, 240}}
2010-10-15 15:40:42.387 SizeToFit[14953:207] theView.sizeThatFits: {322, 240}
2010-10-15 15:40:43.389 SizeToFit[14953:207] theView.bounds: {{0, 0}, {322, 240}}
2010-10-15 15:40:43.391 SizeToFit[14953:207] theView.sizeThatFits: {322, 240}
Run Code Online (Sandbox Code Playgroud)
我必须在这里遗漏一些东西.
谢谢.
Ole*_*ann 51
文档非常明确.-sizeToFit几乎调用-sizeThatFits:(可能以视图的当前大小作为参数),默认实现-sizeThatFits:几乎没有(它只返回其参数).
一些UIView子类覆盖-sizeThatFits:了更有用的东西(例如UILabel).如果您想要任何其他功能(例如调整视图大小以适合其子视图),您应该继承UIView并覆盖-sizeThatFits:.
如果你不覆盖 UIView,你可以只使用扩展。
迅速:
extension UIView {
func sizeToFitCustom () {
var size = CGSize(width: 0, height: 0)
for view in self.subviews {
let frame = view.frame
let newW = frame.origin.x + frame.width
let newH = frame.origin.y + frame.height
if newW > size.width {
size.width = newW
}
if newH > size.height {
size.height = newH
}
}
self.frame.size = size
}
}
Run Code Online (Sandbox Code Playgroud)
相同的代码,但速度提高了 3 倍:
extension UIView {
final func sizeToFitCustom() {
var w: CGFloat = 0,
h: CGFloat = 0
for view in subviews {
if view.frame.origin.x + view.frame.width > w { w = view.frame.origin.x + view.frame.width }
if view.frame.origin.y + view.frame.height > h { h = view.frame.origin.y + view.frame.height }
}
frame.size = CGSize(width: w, height: h)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28947 次 |
| 最近记录: |