Light's Blog

The best or nothing.

iOS知识小集-170911

| Comments

长按语音控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
-(void)setupBtn{
  //  按下按钮
  [self.voiceBtn addTarget:self action:@selector(btnTouchBegin:) forControlEvents:UIControlEventTouchDown];
  //  立刻松开
  [self.voiceBtn addTarget:self action:@selector(btnTouchEnd:) forControlEvents:UIControlEventTouchUpInside];
  //  上划取消
  [self.voiceBtn addTarget:self action:@selector(cancelSpeak) forControlEvents:UIControlEventTouchDragExit];
  //  外部松开
  [self.voiceBtn addTarget:self action:@selector(btnTouchEnd:) forControlEvents:UIControlEventTouchUpOutside];
}

//  通过计时器区分“点击”还是“长按”
- (void)btnTouchBegin:(UIButton *)button {
  self.countNum = 0.0f;
  self.timer =
      [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(handleTimer) userInfo:nil repeats:YES];
  [self.timer fire];
}

- (void)btnTouchEnd:(UIButton *)button {
  [self.timer invalidate];

  if ([self isLongPressGesture]) {
    //  执行长按操作
  } else {
    //  执行点击操作
  }
}

// 处理时间
- (void)handleTimer {
  self.countNum += 0.1;

  if ([self isLongPressGesture]) {
    [self.timer invalidate];
    [self longPressVoiceBegin];
  }
}

// 判断是否为长按手势
- (BOOL)isLongPressGesture {
  return self.countNum >= 0.5;
}

// 上划取消语音输入
- (void)cancelSpeak {
  [self voiceEnd];
}

长按手势控制

添加长按手势

1
2
3
4
- (void)addLongPressGesture{
  UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureAction:)];
  [self.voiceBtn addGestureRecognizer:longPressGesture];
}

处理长按手势

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
- (void)longPressGestureAction:(UILongPressGestureRecognizer *)longPress {
  CGPoint point = [longPress locationInView:self.voiceBtn];
  switch (longPress.state) {
    case UIGestureRecognizerStateBegan:
      //  长按手势开始
      break;
    case UIGestureRecognizerStateChanged:
      //  长按滑动
      break;
    case UIGestureRecognizerStateEnded:
      //  长按手势结束
      break;
    default:
      break;
  }
}

//  判断触点是否在特定区域内
- (BOOL)isInViewAreaWithTouchPoint:(CGPoint)touchPoint {
  return touchPoint.y > 0;
}

Comments