gpt4 book ai didi

ios - UIButton PanGesture 离开屏幕

转载 作者:行者123 更新时间:2023-11-28 19:04:55 25 4
gpt4 key购买 nike

我构建了一个小型测试应用程序以在 UIButton 上应用平移手势。我成功应用了平移手势并成功移动了按钮。但问题是我什至可以将按钮移到屏幕外。如何将其绑定(bind)为仅在 iPhone 屏幕内移动?这是我的代码:

    - (void)viewDidLoad
{
[super viewDidLoad];

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[panGesture setMinimumNumberOfTouches:1];
[_shareButton addGestureRecognizer:panGesture];
}

-(IBAction)pan:(UIPanGestureRecognizer *)recognizer
{
CGPoint trans =[recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x+trans.x, recognizer.view.center.y+trans.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];


}

如何限制按钮移出屏幕?我正在使用 iOS 7,xcode 5.0。

最佳答案

这对你有用..但我是用 Swift 写的:

func callMe(sender: UIPanGestureRecognizer)
{
let translation = sender.translationInView(self.view)

let newX = sender.view!.center.x + translation.x
let newY = sender.view!.center.y + translation.y
let senderWidth = sender.view!.bounds.width / 2
let senderHight = sender.view!.bounds.height / 2

if newX <= senderWidth
{
sender.view!.center = CGPoint(x: senderWidth, y: sender.view!.center.y + translation.y)
}
else if newX >= self.view.bounds.maxX - senderWidth
{
sender.view!.center = CGPoint(x: self.view.bounds.maxX - senderWidth, y: sender.view!.center.y + translation.y)
}
if newY <= senderHight
{
sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: senderHight)
}
else if newY >= self.view.bounds.maxY - senderHight
{
sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: self.view.bounds.maxY - senderHight)
}
else
{
sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: sender.view!.center.y + translation.y)
}

sender.setTranslation(CGPointZero, inView: self.view)
}

我希望它能帮助任何正在寻找最简单方法的人。

关于ios - UIButton PanGesture 离开屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21349619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com