在 iOS 開發中,畫面的一切都建立在 UIView 之上。本文把日常最常翻查的 UIView 操作整理成一份速查筆記,從視圖層級、幾何運算一路到動畫與轉場。
若想在稍後執行某個方法,可使用 NSObject 提供的 performSelector: 系列:
performSelector: performSelector:withObject: performSelector:withObject:withObject: // 實際調用:一秒後執行 displayViews [self performSelector:@selector(displayViews) withObject:nil afterDelay:1.0f];
// 父視圖 [self.view superview] // 所有子視圖 [self.view subviews] // 所處的 window self.view.window
NSArray *allSubviews(UIView *aView)
{
NSArray *results = [aView subviews];
for (UIView *eachView in [aView subviews])
{
NSArray *riz = allSubviews(eachView);
if (riz) {
results = [results arrayByAddingObjectsFromArray:riz];
}
}
return results;
}
// Return all views throughout the application
NSArray *allApplicationViews()
{
NSArray *results = [[UIApplication sharedApplication] windows];
for (UIWindow *window in [[UIApplication sharedApplication] windows])
{
NSArray *riz = allSubviews(window);
if (riz) results = [results arrayByAddingObjectsFromArray:riz];
}
return results;
}
NSArray *pathToView(UIView *aView)
{
NSMutableArray *array = [NSMutableArray arrayWithObject:aView];
UIView *view = aView;
UIWindow *window = aView.window;
while (view != window)
{
view = [view superview];
[array insertObject:view atIndex:0];
}
return array;
}
addSubview: // 加入子視圖 bringSubviewToFront: // 移到最前方 sendSubviewToBack: // 移到最後方 removeFromSuperview // 從父視圖移除 insertSubview:atIndex: // 插入並指定索引 insertSubview:aboveSubview: // 插入到某視圖之上 insertSubview:belowSubview: // 插入到某視圖之下 exchangeSubviewAtIndex:withSubviewAtIndex: // 交換兩個位置的視圖
(void)didAddSubview:(UIView *)subview // 加入子視圖完成後 (void)didMoveToSuperview // 移動完成後 (void)didMoveToWindow // 移動到新的 window 後 (void)willRemoveSubview:(UIView *)subview // 移除子視圖之後 (void)didMoveToSuperview:(UIView *)subview // 移動視圖之前 (void)didMoveToWindow // 移動到 window 之前
myview.tag = 1001; [self.view viewWithTag:1001]; (UILabel *)[self.view.window viewWithTag:1001];
struct CGPoint { CGFloat x; CGFloat y; };
struct CGSize { CGFloat width; CGFloat height; };
struct CGRect { CGPoint origin; CGSize size; };
CGRect rect = CGRectMake(0, 0, 320, 480);
UIView *view = [[UIView alloc] initWithFrame:rect];
// 字串轉結構
CGPointFromString(@"{3.0,2.5}"); // {x,y}
CGRectFromString(@"{{3,2},{4,5}}"); // {{x,y},{w,h}}
CGSizeFromString(@"{3.0,2.5}"); // {w,h}
// 結構轉字串
NSStringFromCGPoint(point);
NSStringFromCGRect(rect);
NSStringFromCGSize(size);
// 以中心為基準縮放矩形:正值變小,負值變大
CGRectInset(rect, dx, dy);
// 判斷兩矩形是否相交
CGRectIntersectsRect(rect1, rect2);
// 零值常量
CGPointZero; CGRectZero; CGSizeZero;
// 建立
CGPointMake(x, y);
CGRectMake(x, y, width, height);
CGSizeMake(width, height);
CGRectGetMinX / CGRectGetMinY
CGRectGetMidX / CGRectGetMidY // X、Y 的中間值
CGRectGetMaxX / CGRectGetMaxY
// 直接設定中心
myview.center = CGPointMake(100, 200);
// 定義內縮邊界
typedef struct UIEdgeInsets {
CGFloat top, left, bottom, right; // 正值為內縮,負值為向外擴
} UIEdgeInsets;
UIEdgeInsets insets = UIEdgeInsetsMake(5, 5, 5, 5);
CGRect innerRect = UIEdgeInsetsInsetRect([aView bounds], insets);
CGRect subRect = CGRectInset(innerRect,
self.frame.size.width / 2.0f,
self.frame.size.height / 2.0f);
// 建立 CGAffineTransform t = CGAffineTransformMakeRotation(angle); // 旋轉,angle 以 0~2*PI 較合適 CGAffineTransform t = CGAffineTransformMakeScale(0.5f, 0.5f); // 縮放 CGAffineTransform t = CGAffineTransformMakeTranslation(50, 60); // 位移 // 修改 CGAffineTransform scaled = CGAffineTransformScale(transform, degree, degree); CGAffineTransform moved = CGAffineTransformTranslate(t, tx, ty); CGAffineTransform roted = CGAffineTransformRotate(t, angle); // 套用與還原 [self.view setTransform:scaled]; myview.transform = CGAffineTransformMakeRotation(PI); myview.transform = CGAffineTransformIdentity;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1f
target:self
selector:@selector(move:)
userInfo:nil
repeats:YES];
// 讓目前執行緒休眠一秒
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0f]];
CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:1.0]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(animationFinished:)]; // 在中間段落放入要變化的屬性 [[self.view viewWithTag:999] setAlpha:1.0f]; [UIView commitAnimations];
UIView *whiteBackdrop = [self.view viewWithTag:100];
if ([(UISegmentedControl *)self.navigationItem.titleView selectedSegmentIndex]) {
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
forView:whiteBackdrop
cache:YES];
} else {
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight
forView:whiteBackdrop
cache:YES];
}
NSInteger purple = [[whiteBackdrop subviews] indexOfObject:[whiteBackdrop viewWithTag:999]];
NSInteger maroon = [[whiteBackdrop subviews] indexOfObject:[whiteBackdrop viewWithTag:998]];
[whiteBackdrop exchangeSubviewAtIndex:purple withSubviewAtIndex:maroon];
// 可選的轉場種類
typedef enum {
UIViewAnimationTransitionNone,
UIViewAnimationTransitionFlipFromLeft,
UIViewAnimationTransitionFlipFromRight,
UIViewAnimationTransitionCurlUp,
UIViewAnimationTransitionCurlDown,
} UIViewAnimationTransition;
CATransition *animation = [CATransition animation];
animation.delegate = self;
animation.duration = 4.0f;
animation.timingFunction = UIViewAnimationCurveEaseInOut;
// type:Fade、MoveIn、Push、Reveal
switch ([(UISegmentedControl *)self.navigationItem.titleView selectedSegmentIndex]) {
case 0: animation.type = kCATransitionFade; break;
case 1: animation.type = kCATransitionMoveIn; break;
case 2: animation.type = kCATransitionPush; break;
case 3: animation.type = kCATransitionReveal; break;
default: break;
}
// subtype:轉場方向
if (isLeft)
animation.subtype = kCATransitionFromRight;
else
animation.subtype = kCATransitionFromLeft;
UIView *whitebg = [self.view viewWithTag:10];
NSInteger purple = [[whitebg subviews] indexOfObject:[whitebg viewWithTag:99]];
NSInteger white = [[whitebg subviews] indexOfObject:[whitebg viewWithTag:100]];
[whitebg exchangeSubviewAtIndex:purple withSubviewAtIndex:white];
[[whitebg layer] addAnimation:animation forKey:@"animation"];
// type 也可以使用字串指定更多效果
// cube、suckEffect、oglFlip、rippleEffect、pageCurl、pageUnCurl、
// cameraIrisHollowOpen、cameraIrisHollowClose
NSMutableArray *bflies = [NSMutableArray array];
for (int i = 1; i <= 17; i++) {
[bflies addObject:[UIImage imageWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"bf_%d", i]
ofType:@"png"]]];
}
UIImageView *butterflyView = [[UIImageView alloc]
initWithFrame:CGRectMake(40.0f, 300.0f, 60.0f, 60.0f)];
butterflyView.tag = 300;
butterflyView.animationImages = bflies;
butterflyView.animationDuration = 0.75f;
[self.view addSubview:butterflyView];
[butterflyView startAnimating];
[butterflyView release];
這份清單涵蓋了 UIView 最常被查詢的幾類操作。值得一提的是,範例中的 begin/commit 動畫與手動 retain/release 屬於舊寫法,在現代專案中建議改用 animateWithDuration:animations: 區塊式動畫與 ARC,程式碼會短很多,也不容易出錯。