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

用 UIWindow 自定義 AlertView:最基礎的實現思路

編輯:iOS 相關資訊

系統自帶的 UIAlertView 樣式有限,當設計稿要求自定義彈窗時,一個常見做法是新建一個 UIWindow 子類,把彈窗當作獨立窗口浮在頂層。下面是最基礎的實現骨架。

一、頭文件

#import <UIKit/UIKit.h>

@interface ABCustomAlertView : UIWindow

// 顯示
- (void)show;
// 消失
- (void)dismiss;

@end

二、實現文件

#import "ABCustomAlertView.h"

@implementation ABCustomAlertView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.windowLevel = UIWindowLevelAlert;

        // 注意:不要設置 UIWindow 的 alpha 屬性,
        // 它會連帶影響所有子視圖的透明度。
        // 這裡改用一張半透明的背景圖來實現遮罩效果
        self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"alert_bg.png"]];

        UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 80)] autorelease];
        view.backgroundColor = [UIColor blackColor];
        view.center = CGPointMake(160, 240);
        [self addSubview:view];
    }
    return self;
}

- (void)show {
    [self makeKeyAndVisible];
}

- (void)dismiss {
    [self resignKeyWindow];
    [self release];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // 點擊任意位置即可關閉
    [self dismiss];
}

@end

三、幾個關鍵點

  • windowLevel 設為 UIWindowLevelAlert,確保彈窗浮在普通界面之上。

  • 遮罩不要用 window 的 alpha,否則子視圖也會一起變透明。用半透明圖片或自定義 view 的 backgroundColor 更可控。

  • makeKeyAndVisible 讓窗口成為第一響應者並顯示;resignKeyWindow 則是撤銷焦點。兩者要成對出現。

  • 示例採用 MRC 寫法,dismiss 中直接 release。若項目使用 ARC,去掉這行即可,但要留意 self 的持有關係,避免循環引用導致窗口無法釋放。

這只是最基礎的思路,把自定義的控件、佈局和代理加上去,調用方只需要 show 與 dismiss 兩個方法就能完成顯示與關閉。

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