今天是下大雨,今天乘著下雨天來學習一下UIView的基礎??... 拒絕慌不擇路的寫代碼
1. CGRectInset(rect,dx,dy) 平移和縮放
CGRect rect = CGRectMake(100, 100, 100 , 100);
UIView *testView = [[UIView alloc] initWithFrame:rect];
testView.backgroundColor = [UIColor redColor];
[self.view addSubview: testView];
CGRect rect1 = CGRectInset(rect, 30, 10);
NSLog(@"%@",NSStringFromCGRect(rect1));
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[UIView animateWithDuration:0.25 animations:^{
testView.frame = rect1;
}];
});
控制臺打印: {{130, 110}, {40, 80}}
CGRectInset(rect,dx,dy)
- rect是原來的frame
- dx為正則origin x加上dx,為負數則減(PS.其實都是加,加上一個負數就是減啊)
- dy 和dx一樣處理 y加上dy
- rect的size大小則是
width是(rect.size.width - dx*2)height是 (rect.size.height - dy*2) 就是dx越大縮放的寬度越小 dy越大縮放的高度度越小
(正縮小 負增大)
2. CGRectOffset(rect,dx,dy) 僅僅只是平移
CGRect rect = CGRectMake(100, 100, 100 , 100);
UIView *testView = [[UIView alloc] initWithFrame:rect];
testView.backgroundColor = [UIColor redColor];
[self.view addSubview: testView];
CGRect rect1 = CGRectOffset(rect, 30, 30);
NSLog(@"%@",NSStringFromCGRect(rect1));
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[UIView animateWithDuration:0.25 animations:^{
testView.frame = rect1;
}];
});
- 與
CGRectInset(rect,dx,dy)同理,唯一區(qū)別就是size不變, 只有x和y的變化
3. convertRect: toView: 切換坐標系 也就是坐標變 大小不變
從一個子視圖從父視圖移除加到其他視圖的上,需要重新計算frame,然鵝這個API就免去了去書寫計算的步驟
CGRect rect = CGRectMake(100, 100, 100 , 100);
UIView *testView = [[UIView alloc] initWithFrame:rect];
testView.backgroundColor = [UIColor redColor];
[self.view addSubview: testView];
CGRect rect1 = CGRectMake(30, 30, 60 , 60);
UIView *subView = [[UIView alloc] initWithFrame:rect1];
subView.backgroundColor = [UIColor greenColor];
[testView addSubview: subView];
CGRect frame = [subView convertRect:subView.bounds toView: self.view];
NSLog(@"%@",NSStringFromCGRect(frame));
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[UIView animateWithDuration:0.25 animations:^{
[subView removeFromSuperview];
subView.frame = frame;
[self.view addSubview: subView];
}];
});
轉換前的坐標 ==> {{30, 30}, {60, 60}}
轉換后的坐標 ==> {{130, 130}, {60, 60}}
- scrollView里的子控件里的子控件如何確定在scrollView里的位置的一個方案, 還有就是tableview通過cell獲取在tableview上的位置