尝试这个
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
aButton.frame = CGRectMake(xValue, yValue, 45, 45);
[aButton addTarget:self action:@selector(holdDown) forControlEvents:UIControlEventTouchDown];
[aButton addTarget:self action:@selector(holdRelease) forControlEvents:UIControlEventTouchUpInside];
- (void)holdDown
{
NSLog(@"hold Down");
}
- (void)holdRelease
{
NSLog(@"hold release");
}
对于 NSPratik 的情况:你可以使用事件UIControlEventTouchUpOutside
如果用户长按按钮并在一段时间后,而不是释放手指,用户会将他/她的手指移出按钮的边界。只需再添加一个事件。
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
aButton.frame = CGRectMake(xValue, yValue, 45, 45);
[aButton addTarget:self action:@selector(holdDown) forControlEvents:UIControlEventTouchDown];
[aButton addTarget:self action:@selector(holdRelease) forControlEvents:UIControlEventTouchUpInside];
[aButton addTarget:self action:@selector(holdReleaseOutSide) forControlEvents:UIControlEventTouchUpOutside]; //add this for your case releasing the finger out side of the button's frame
//add this method along with other methods
- (void)holdReleaseOutSide
{
NSLog(@"hold release out side");
}
斯威夫特版本
var aButton:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
aButton.frame = CGRectMake(xValue,yValue, 45, 45)
aButton.setTitle("aButton", forState: UIControlState.Normal)
aButton.backgroundColor = UIColor.greenColor()
aButton.addTarget(self, action: Selector("holdRelease:"), forControlEvents: UIControlEvents.TouchUpInside);
aButton.addTarget(self, action: Selector("HoldDown:"), forControlEvents: UIControlEvents.TouchDown)
self.addSubview(aButton)
//target functions
func HoldDown(sender:UIButton)
{
print("hold down")
}
func holdRelease(sender:UIButton)
{
print("hold release")
}