您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 開發:UIView 常用語法與動畫技巧總整理

編輯:iOS 相關資訊

在 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;
}

取得整個 App 中所有的視圖

// 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;
}

取得從 window 到某視圖的完整父鏈

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 之前

五、以 tag 標記並檢索視圖

myview.tag = 1001;
[self.view viewWithTag:1001];
(UILabel *)[self.view.window viewWithTag:1001];

六、幾何運算:CGPoint、CGSize、CGRect

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]];

十、 traditional 動畫塊

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;

十二、以 QuartzCore 製作 CATransition

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,程式碼會短很多,也不容易出錯。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved