触摸滑过UIButton问题

时间:2015-02-04 21:00:45

标签: objective-c swift

有人能告诉我是否已将前两行正确翻译为Swift并且第一部分是否正确?此外,任何人都可以帮助我找出其余部分。我无法弄清楚如何在底部翻译if语句..

[C addTarget:self action:@selector(outsideOfKey: forEvent:) forControlEvents:UIControlEventTouchDragOutside|UIControlEventTouchDragInside];
[C addTarget:self action:@selector(keyGetsLeft: forEvent:) forControlEvents:UIControlEventTouchUpOutside | UIControlEventTouchUpInside];


-(void) outsideOfKey:(id)sender forEvent:(UIEvent *)event
{    
    for(UITouch *t in [event allTouches])
{

        CGPoint touchPoint = [t locationInView:window];
        if(CGRectContainsPoint(C.frame, touchPoint))
         {
             C.highlighted = YES;
         }
        else{
            C.highlighted = NO;
        }

转换为swift

C.addTarget(self, action:Selector("outsideOfKey:forEvent:"), forControlEvents:.TouchDragOutside)
    C.addTarget(self, action:Selector("outsideOfKey:forEvent:"), forControlEvents:.TouchDragInside)
    C.addTarget(self, action:Selector("keyGetsLeft:forEvent:"), forControlEvents:.TouchUpOutside)
    C.addTarget(self, action:Selector("keyGetsLeft:forEvent:"), forControlEvents:.TouchUpInside)


func outsideOfKey (sender: AnyObject, forEvent: UIEvent) {


    let touch = event.allTouches() as? UITouch

        for touch
        {
            var touchPoint : CGPoint = touch.locationInView(window)

            if(CGRectContainsPoint(C.frame, touchPoint))
            {
                C.highlighted = YES;
            }
            else{
                C.highlighted = NO;
            }

}

1 个答案:

答案 0 :(得分:0)

尝试类似:

C.addTarget(self, action:Selector("outsideOfKey:forEvent:"), forControlEvents:.TouchDragOutside | .TouchDragInside)
C.addTarget(self, action:Selector("keyGetsLeft:forEvent:"), forControlEvents:.TouchUpOutside | .TouchUpInside)


func outsideOfKey(sender: AnyObject, forEvent event: UIEvent) {

    if let touches = event.allTouches()?.allObjects as? [UITouch] {

        for touch in touches {
            var touchPoint : CGPoint = touch.locationInView(window)

            if CGRectContainsPoint(C.frame, touchPoint) == true {
                C.highlighted = true;
            } else {
                C.highlighted = false;
            }
        }
    }
}

点数:

  • 您仍然可以使用" |"在swift(大多数时间)的枚举上运算符
  • 你不要在swift
  • 中的条件句子周围加上括号
  • 是和否在swift中无效,你多用真假
  • Swift不支持集合,因此最简单的方法是将数据作为数组进行迭代,以便您可以使用简单的swift进行迭代... in in循环
  • "如果让..."如果右侧不是nil"触及"则模式称为可选绑定。将被设置为值,并将执行以下大括号中的代码,否则将跳过代码块
  • 方式"?"在" .allTouches()"之后使用被称为可选链接,如果.allTouches()返回nil,整个表达式将返回nil

希望这对您有用,请告诉我您是否有更快捷的查询!