首頁 > 軟體

iOS實現全域性懸浮按鈕

2022-03-21 16:00:59

本文範例為大家分享了iOS實現全域性懸浮按鈕的具體程式碼,供大家參考,具體內容如下

現在有很多app都做這個全域性按鈕

如上面兩張圖的效果,完成一個全域性懸浮的按鈕,而且不會劃出螢幕外
既然是全域性,那寫在AppDelegate中
UIWindow是一種特殊的UIView,它相當於一塊畫框,而UIView相當於裡面的畫布。通常在一個app中只會有一個UIWindow。

AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UIButton *button;

@end

AppDelegate.m

先button懶載入

- (UIButton*)button {
    if (!_button) {
        _button = [UIButton buttonWithType:UIButtonTypeCustom];
        _button.frame = CGRectMake(258, 450, 60, 60);//初始在螢幕上的位置
        [_button setImage:[UIImage imageNamed:@"bcl_btn_whole"] forState:UIControlStateNormal];
    }
    return _button;
}

然後將其加在window上,設定手勢

-(void)createButton{
    if (!_button) {
        _window = [[UIApplication sharedApplication] keyWindow];
        _window.backgroundColor = [UIColor whiteColor];
        [_window addSubview:self.button];
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:
                                       self action:@selector(locationChange:)];
        pan.delaysTouchesBegan = YES;
        [_button addGestureRecognizer:pan];
    }
}

這個呢是為了開機啟動兩秒後建立全域性button

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self performSelector:@selector(createButton) withObject:nil afterDelay:2];
}

最關鍵的就是設定button不要劃出螢幕外
以下四個else if分別為螢幕的上下左右
設定一個標記值isOVer
如果超出螢幕範圍,糾正回來

-(void)locationChange:(UIPanGestureRecognizer*)p{
    CGFloat HEIGHT=_button.frame.size.height;
    CGFloat WIDTH=_button.frame.size.width;
    BOOL isOver = NO;
    CGPoint panPoint = [p locationInView:[UIApplication sharedApplication].windows[0]];
    CGRect frame = CGRectMake(panPoint.x, panPoint.y, HEIGHT, WIDTH);
    NSLog(@"%f--panPoint.x-%f-panPoint.y-", panPoint.x, panPoint.y);
    if(p.state == UIGestureRecognizerStateChanged){
        _button.center = CGPointMake(panPoint.x, panPoint.y);
    }
    else if(p.state == UIGestureRecognizerStateEnded){
        if (panPoint.x + WIDTH > KScreenWidth) {
            frame.origin.x = KScreenWidth - WIDTH;
            isOver = YES;
        } else if (panPoint.y + HEIGHT > KScreenHeight) {
            frame.origin.y = KScreenHeight - HEIGHT;
            isOver = YES;
        } else if(panPoint.x - WIDTH / 2< 0) {
            frame.origin.x = 0;
            isOver = YES;
        } else if(panPoint.y - HEIGHT / 2 < 0) {
            frame.origin.y = 0;
            isOver = YES;
        }
        if (isOver) {
            [UIView animateWithDuration:0.3 animations:^{
                self.button.frame = frame;
            }];
        }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com