標籤:
項目中需要在建立一個懸浮按鈕,自己覺得光建立一個按鈕不能滑動有點不太最佳化,就自己試著做了一個可以隨意拖動的懸浮按鈕,希望大家能夠多多支援。
-(void)viewDidLoad{//建立懸浮按鈕 self.editEventsButton=[UIButton buttonWithType:UIButtonTypeCustom]; self.editEventsButton.frame=CGRectMake(0, 0, 60, 60); [self.editEventsButton setBackgroundImage:[UIImage imageNamed:@"問醫生"] forState:UIControlStateNormal]; [self.editEventsButton addTarget:self action:@selector(gotoEditEvents) forControlEvents:UIControlEventTouchUpInside]; self.window=[[UIWindow alloc] initWithFrame:CGRectMake(ScreenWidth-55, ScreenHeight-75-CGRectGetHeight(self.chartView.frame), 60, 60)]; self.window.windowLevel=UIWindowLevelAlert+1; self.window.backgroundColor=[UIColor clearColor]; self.window.layer.cornerRadius=20; self.window.layer.masksToBounds=YES; [self.window addSubview:self.editEventsButton]; [self.window makeKeyAndVisible]; //放一個拖動手勢,用來改變控制項的位置 UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(changePostion:)]; [self.editEventsButton addGestureRecognizer:pan]; [self charts]; [self tabarTool];}//手勢事件 -- 改變位置-(void)changePostion:(UIPanGestureRecognizer *)pan{ CGPoint point = [pan translationInView:self.window]; CGFloat width = [UIScreen mainScreen].bounds.size.width; CGFloat height = [UIScreen mainScreen].bounds.size.height; CGRect originalFrame = self.window.frame; if (originalFrame.origin.x >= 0 && originalFrame.origin.x+originalFrame.size.width <= width) { originalFrame.origin.x += point.x; } if (originalFrame.origin.y >= 0 && originalFrame.origin.y+originalFrame.size.height <= height) { originalFrame.origin.y += point.y; } self.window.frame = originalFrame; [pan setTranslation:CGPointZero inView:self.view]; if (pan.state == UIGestureRecognizerStateBegan) { _editEventsButton.enabled = NO; }else if (pan.state == UIGestureRecognizerStateChanged){ } else { CGRect frame = self.window.frame; //記錄是否越界 BOOL isOver = NO; if (frame.origin.x < 0) { frame.origin.x = 0; isOver = YES; } else if (frame.origin.x+frame.size.width > width) { frame.origin.x = width - frame.size.width; isOver = YES; } if (frame.origin.y < 0) { frame.origin.y = 0; isOver = YES; } else if (frame.origin.y+frame.size.height > height) { frame.origin.y = height - frame.size.height; isOver = YES; } if (isOver) { [UIView animateWithDuration:0.3 animations:^{ self.window.frame = frame; }]; } _editEventsButton.enabled = YES; }}
iOS開發——懸浮按鈕