你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS-懸浮按鈕

iOS-懸浮按鈕

編輯:IOS開發綜合

在項目中可能會有這種需求,即在一個界面最頂層需要一個按鈕,這個按鈕可能是發布信息功能,也可能是回到頂部.這樣我們可以使用UIwindow這個神奇的控件實現,很簡單.

完整項目源碼:
https://github.com/qxuewei/XWSuspendBtn

最終實現效果如下:
這裡寫圖片描述

實現邏輯:
1.在需要出現懸浮按鈕的類中聲明按鈕UIButton屬性和UIWindow屬性<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:java;"> /** window */ @property (nonatomic, strong) UIWindow *window; /** 懸浮按鈕 */ @property (nonatomic, strong) UIButton *button;

2.創建UIWindow以及懸浮按鈕方法

-(void)creatSuspendBtn{
    //懸浮按鈕
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    [_button setImage:[UIImage imageNamed:@"plus"] forState:UIControlStateNormal];
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    _button.frame = CGRectMake(0,0, 64, 64);
    [_button addTarget:self action:@selector(suspendBtnClick) forControlEvents:UIControlEventTouchUpInside];

    //懸浮按鈕所處的頂端UIWindow
    _window = [[UIWindow alloc] initWithFrame:CGRectMake(screenWidth*0.5-32, screenHeight-84, 64, 64)];
    //使得新建window在最頂端
    _window.windowLevel = UIWindowLevelAlert + 1;
    _window.backgroundColor = [UIColor clearColor];
    [_window addSubview:_button];
    //顯示window
    [_window makeKeyAndVisible];
}

3.初始化視圖時創建懸浮按鈕

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.mainTableView setDelegate:self];
    [self.mainTableView setDataSource:self];

    //延時加載window,注意我們需要在rootWindow創建完成之後再創建這個懸浮的按鈕
    [self performSelector:@selector(creatSuspendBtn) withObject:nil afterDelay:0.2];

}

項目github地址:
https://github.com/qxuewei/XWSuspendBtn

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