我已经创建了 UIView
的 mainView 对象并在其上添加了一个 subview 。我在 mainView 上应用了变换以减小帧大小。但是主视图的 subview 框架并没有减少。如何减小此 subview 的大小。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CGFloat widthM=1200.0;
CGFloat heightM=1800.0;
UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, widthM, heightM)];
mainView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"te.png"]];
[self.view addSubview:mainView];
CGFloat yourDesiredWidth = 250.0;
CGFloat yourDesiredHeight = yourDesiredWidth *heightM/widthM;
CGAffineTransform scalingTransform;
scalingTransform = CGAffineTransformMakeScale(yourDesiredWidth/mainView.frame.size.width, yourDesiredHeight/mainView.frame.size.height);
mainView.transform = scalingTransform;
mainView.center = self.view.center;
NSLog(@"mainView:%@",mainView);
UIView *subMainView= [[UIView alloc] initWithFrame:CGRectMake(100, 100, 1000, 1200)];
subMainView.backgroundColor = [UIColor redColor];
[mainView addSubview:subMainView];
NSLog(@"subMainView:%@",subMainView);
}
这些 View 的 NSlog:
mainView:<UIView: 0x8878490; frame = (35 62.5; 250 375); transform = [0.208333, 0, 0, 0.208333, 0, 0]; layer = <CALayer: 0x8879140>>
subMainView:<UIView: 0x887b8c0; frame = (100 100; 1000 1200); layer = <CALayer: 0x887c160>>
这里主视图的宽度是250, subview 的宽度是1000。但是当我在模拟器中得到输出时, subview 被正确占用,但它没有穿过主视图。怎么可能?转换后如何获取与主视图框架相关的 subview 框架?
最佳答案
您看到的是预期行为。 UIView
的框架是相对于其父 View 的,因此当您对其父 View 应用转换时它不会改变。虽然 View 也会出现“扭曲”,但框架不会反射(reflect)更改,因为它仍然相对于其父级处于完全相同的位置。
但是,我假设您想要获取相对于最顶层 UIView
的 View 框架。在那种情况下,UIKit 提供了这些功能:
– [UIView convertPoint:toView:]
– [UIView convertPoint:fromView:]
– [UIView convertRect:toView:]
– [UIView convertRect:fromView:]
我将这些应用于您的示例:
CGRect frame = [[self view] convertRect:[subMainView frame] fromView:mainView];
NSLog(@"subMainView:%@", NSStringFromCGRect(frame));
这是输出:
subMainView:{{55.8333, 83.3333}, {208.333, 250}}
关于ios - 如何在主视图上应用变换后获取 subview 的框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16392690/