我需要一些认真的帮助。我正在目标c中构建键盘应用程序,而我拥有的功能之一是在键盘屏幕周围拖动键盘按钮,以便用户可以将它们放置在任何位置。但是我的问题是,我无法弄清楚如何在拖动后保存每个按钮的位置,以便在用户关闭然后再打开时,所有键盘按钮都位于用户之前放置它们的位置。
我的代码如下:
这在我的viewDidLoad中:
for (UIButton *button in self.allButtonsArray) {
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]
initWithTarget:self
action:@selector(handlePanGestureButtons:)];
[button addGestureRecognizer:panGestureRecognizer];
}
平移方法:
(void) handlePanGestureButtons:(UIPanGestureRecognizer *)gesture {
NSString *_valueOfDragging= [defaults stringForKey:@"stateOfSwitchButtonDragging"];
if([_valueOfDragging compare:@"ON"] == NSOrderedSame){
if (gesture.state==UIGestureRecognizerStateChanged || gesture.state == UIGestureRecognizerStateEnded){
UIView *superview = gesture.view.superview;
CGSize superviewSize = superview.bounds.size;
CGSize thisSize = gesture.view.frame.size;
CGPoint translation = [gesture translationInView:self.view];
CGPoint center = CGPointMake(gesture.view.center.x + translation.x,
gesture.view.center.y + translation.y);
CGPoint resetTranslation = CGPointMake(translation.x, translation.y);
if(center.x - thisSize.width/2 < 0)
center.x = thisSize.width/2;
else if (center.x + thisSize.width/2 > superviewSize.width)
center.x = superviewSize.width-thisSize.width/2;
else
resetTranslation.x = 0;
if(center.y - thisSize.height/2 < 0)
center.y = thisSize.height/2;
else if(center.y + thisSize.height/2 > superviewSize.height)
center.y = superviewSize.height-thisSize.height/2;
else
resetTranslation.y = 0; //Only reset the vertical translation if the view *did* translate vertically
gesture.view.center = center;
[gesture setTranslation:CGPointMake(0, 0) inView:self.view];
}
}
答案 0 :(得分:1)
您可以将所有坐标存储在NSUserDefaults
中,您可以在打开应用时再次访问。由于坐标是CGPoint
值,因此您需要先使用NSStringFromCGPoint
将它们转换为字符串对象。然后,您可以使用所有按钮的坐标创建一个数组,并将它们写入您的用户默认设置。为了能够识别每个按钮,可以制作一个结构数组,例如:
struct KeyCoordinate {
NSString *keyIdentifier;
NSString *keyCoordinate;
}
struct KeyCoordinate keyCoordinate1;
struct KeyCoordinate keyCoordinate2;
keyCoordinate1.keyIdentifier = @"key1"
keyCoordinate1.keyCoordinate = NSStringFromCGPoint(key1Point);
keyCoordinate2.keyIdentifier = @"key2"
keyCoordinate2.keyCoordinate = NSStringFromCGPoint(key2Point);
NSArray *buttonCoordinatesArray = @[keyCoordinate1, keyCoordinate2, ...];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
// write:
[userDefaults setObject: buttonCoordinatesArray forKey: @"buttonCoordinatesArray"];
// read:
NSArray *buttonCoordinatesArray = [userDefaults objectForKey: @"buttonCoordinatesArray"];
要从字符串还原为点,请使用CGPointFromString
。
或者,您也可以将点作为NSValue
存储在结构中,但是想法保持不变。