1
我想創建其中有許多動作元素可拖動視圖。爲了做到這一點,我通過Apple文檔複製了代碼,以便從here創建可拖動的視圖。動作要素使用UIPanGestureRecognizer可拖動視圖使視圖轉移
該視圖獲取平移如預期,但是當一個動作元件被點擊視圖轉移到其他位置。這裏是示例代碼和Main.storyboard的複製問題的屏幕截圖。
ViewController.h文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
- (IBAction)segmentedAction:(id)sender;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentOutlet;
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
而且這是在ViewController.m代碼文件
#import "ViewController.h"
@interface ViewController()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
UIView *piece = gestureRecognizer.view;
CGPoint locationInView = [gestureRecognizer locationInView:piece];
CGPoint locationInSuperview = [gestureRecognizer locationInView:piece.superview];
piece.layer.anchorPoint = CGPointMake(locationInView.x/piece.bounds.size.width, locationInView.y/piece.bounds.size.height);
piece.center = locationInSuperview;
}
}
- (IBAction)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
UIView *piece = [gestureRecognizer view];
[self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
CGPoint translation = [gestureRecognizer translationInView:self.view];
[piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y + translation.y)];
[gestureRecognizer setTranslation:CGPointZero inView:self.view];
}
}
- (IBAction)segmentedAction:(id)sender {
self.label.text = [NSString stringWithFormat:@"%ld",self.segmentOutlet.selectedSegmentIndex];
}
@end
任何人都可以指導我一下,我做錯了什麼這裏。
在此先感謝
你試圖移動一組控件上的移動手勢?平視手勢添加到哪個視圖? – Suran
平移手勢被添加到包含分割控件和標籤的視圖中,並且是的,我想移動視圖和其中包含的所有元素 – firecast
此行爲不是因爲觸摸了操作項目,而是在您設置時發生標籤上的文字。註釋行「self.label.text = [NSString stringWithFormat:@」%ld「,self.segmentOutlet.selectedSegmentIndex];」將解決這個問題。但我不知道爲什麼會發生這種情況。 – Suran