iOS-懸浮按鈕

來源:互聯網
上載者:User

標籤:

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

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

最終實現效果如下:

實現邏輯:
1.在需要出現懸浮按鈕的類中聲明按鈕UIButton屬性和UIWindow屬性

/** 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

iOS-懸浮按鈕

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.