1.
2.自定義Button
//
// PopBtn.m
#import "PopBtn.h"
@implementation PopBtn
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
// 目前控件上的點轉換到chatView上
CGPoint chatP = [self convertPoint:point toView:self.chatView];
// 判斷下點在不在chatView上
if ([self.chatView pointInside:chatP withEvent:event]) {
return self.chatView;
}else{
return [super hitTest:point withEvent:event];
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// 擷取UITouch
UITouch *touch = [touches anyObject];
// 擷取目前的點
CGPoint curP = [touch locationInView:self];
// 擷取上一個的點
CGPoint preP = [touch previousLocationInView:self];
// 擷取偏移量
CGFloat offsetX = curP.x - preP.x;
CGFloat OffsetY = curP.y - preP.y;
// 修改控件的位置
CGPoint center = self.center;
center.x += offsetX;
center.y += OffsetY;
self.center = center;
}
@end
3.點選按鈕,彈出
#import "ViewController.h"
#import "PopBtn.h"
@interface ViewController ()
@end
@implementation ViewController
- (IBAction)popChatView:(PopBtn *)sender {
// 彈出對話框
UIButton *chatView = [UIButton buttonWithType:UIButtonTypeCustom];
chatView.bounds = CGRectMake(0, 0, 200, 200);
chatView.center = CGPointMake(100, -100);
[chatView setBackgroundImage:[UIImage imageNamed:@"對話框"] forState:UIControlStateNormal];
[chatView setBackgroundImage:[UIImage imageNamed:@"小孩"] forState:UIControlStateHighlighted];
sender.chatView = chatView;
[sender addSubview:chatView];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
@end
示範: