UIView 的 API 又多又散,寫過幾個專案後反覆查的其實就是那幾十個。以下依主題整理,當成隨手可翻的備忘錄。
performSelector: 系列來自 NSObject,除了直接呼叫,也能帶參數、帶多參數或延遲執行:
performSelector: performSelector:withObject: performSelector:withObject:withObject: // 延遲 1 秒後呼叫 [self performSelector:@selector(displayViews) withObject:nil afterDelay:1.0f];
[self.view superview] // 父視圖 [self.view subviews] // 所有子視圖 self.view.window // 所屬的 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;
}
// 收集全應用內的所有 view
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;
}
// 回傳從 window 一路到該 view 的父層鏈
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)willRemoveSubview:(UIView *)subview // 移除子視圖前 (void)didMoveToSuperview // 移動到父視圖後 (void)willMoveToSuperview:(UIView *)newSuperview (void)didMoveToWindow // 移動到 window 後 (void)willMoveToWindow:(UIWindow *)newWindow
myview.tag = 1001; [self.view viewWithTag:1001]; (UILabel *)[self.view.window viewWithTag:1001];
CGRect rect = CGRectMake(0, 0, 320, 480);
UIView *view = [[UIView alloc] initWithFrame:rect];
// 字串與結構互轉
CGPoint CGPointFromString (NSString *string); // @"{3.0,2.5}"
CGRect CGRectFromString (NSString *string); // @"{{3,2},{4,5}}"
CGSize CGSizeFromString (NSString *string); // @"{3.0,2.5}"
NSString *NSStringFromCGPoint (CGPoint point);
NSString *NSStringFromCGRect (CGRect rect);
NSString *NSStringFromCGSize (CGSize size);
// 以中心為基準縮放矩形:正數縮小,負數放大
CGRect CGRectInset (CGRect rect, CGFloat dx, CGFloat dy);
// 判斷兩矩形是否相交
bool CGRectIntersectsRect (CGRect rect1, CGRect rect2);
// 常用零值與建立函式
const CGPoint CGPointZero;
const CGRect CGRectZero;
const CGSize CGSizeZero;
CGPoint CGPointMake (CGFloat x, CGFloat y);
CGRect CGRectMake (CGFloat x, CGFloat y, CGFloat width, CGFloat height);
CGSize CGSizeMake (CGFloat width, CGFloat height);
CGRectGetMinX / CGRectGetMinY CGRectGetMidX / CGRectGetMidY // 中心座標 CGRectGetMaxX / CGRectGetMaxY myview.center = CGPointMake(100, 200); // 直接設定中心點
// 旋轉 PI 弧度 CGAffineTransform form = CGAffineTransformMakeRotation(M_PI); myview.transform = form; // 復原 myview.transform = CGAffineTransformIdentity; // 建立各種變形 CGAffineTransformMakeRotation(angle); // angle 建議介於 0 ~ 2π CGAffineTransformMakeScale(0.5f, 0.5f); // 縮放 CGAffineTransformMakeTranslation(50, 60); // 位移 // 在既有變形上疊加 CGAffineTransformScale(transform, degree, degree); CGAffineTransformTranslate(CGAffineTransform t, CGFloat tx, CGFloat ty); CGAffineTransformRotate(CGAffineTransform t, CGFloat angle); [self.view setTransform:scaled];
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);
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];
這組 API 已於新版本 SDK 中被 block 版本取代,現行專案建議改用 animateWithDuration:animations:,寫法更短也更安全。
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 = CAMediaTimingFunctionWithName(kCAMediaTimingFunctionEaseInEaseOut);
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;
}
// 設定方向
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"];
animation.type 也可以直接給字串,效果更多花俏:
@"cube" // 立方體翻轉 @"suckEffect" // 吸入 @"oglFlip" // OpenGL 翻轉 @"rippleEffect" // 漣漪 @"pageCurl" / @"pageUnCurl"// 翻頁/反翻頁 @"cameraIrisHollowOpen" // 相機光圈開 @"cameraIrisHollowClose" // 相機光圈關
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1f
target:self
selector:@selector(move:)
userInfo:nil
repeats:YES];
// 讓目前執行緒休眠 1 秒
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0f]];
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]; // MRC 寫法,ARC 下請移除
逐格動畫的關鍵在於 animationImages 的順序與 animationDuration 的匹配:幀數多就給長一點的時間,反之則縮短,這樣播放起來才不會忽快忽慢。記得播放完畢若不再需要,可呼叫 stopAnimating 釋放資源。