我有他们有一些设置的属性帐户。 由于设置有有价值的UISlider
和价值UISwitch
。 当我运行应用程序,它工作正常,我可以从显示的最后一个值NSUserDefaults
,因为viewDidLoad方法的工作原理。 我的应用程序的方式一个标签栏控制器。 所以,当我切换标签,它工作正常一点,因为我可以得到开关和滑块的值,并在viewWillAppear中的方法进行更新。 但在我的设置开关,我提出一个观点,其中有在其中的用户列表,因此用户可以选择任何帐户。 当我从提出看法后,我无法更新开关和滑块的值。 我需要一个触发方法来更新他们的价值观。 有没有办法做到这一点?
Answer 1:
是的,这是第3苹果如何做到这一点:
1) Delegation
2) NSNotificationCenter
3) KVO
然而,对于您的特定情况下,一个模式来看,委托模式是一个苹果建议,是一个我会建议为好。
它需要比其他2个选项虽然多一点的编码。
首先,你必须申报你呈现模态的视图的协议:
in your .h
@protocol MyProtocol;
@interface MyClass : NSObject
@property (nonatomic, weak) id<MyProtocol> delegate;
@end
@protocol MyProtocol <NSObject>
-(void)updateValues:(NSArray *)values;
@end
然后从原始视图控制器模态呈现所述模态视图之前简单地设置这样的delgate
myModallyPresentedController.delegate = self;
然后让你的呈现视图控制器采用的协议
in your .h
MyPresentingViewController : UIViewController <MyProtocol>
in .m
//Implement method:
-(void)updateValues:(NSArray *)values {
//Update Values.
}
最后,当用户按下“完成”
您可以拨打
[delegate updatedValues:myValues];
并相应更新。
希望帮助。
Answer 2:
我前一段时间写了这个,基本上只是将其粘贴到所有这些问题。 顺便说一句,如果任何人有意见,这将使这更容易理解/更好,我很愿意听到他们的声音。
您可以使用委托类之间来回传递信息; 这是您要在使用的方法来传递信息的情况下尤其有用。
Delegates
//In parent .m file:
//assign the delegate
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:@"segueName"])
{
childController *foo = segue.destinationViewController;
foo.delegate = self;
}
}
//implement protocol method(s):
- (void) methodName:(dataType*) dataName
{
//An example of what you could do if your data was an NSDate
buttonLabel.titleLabel.text = [[date description] substringToIndex:10];
}
//In parent .h file:
//import child header
#import "ChildName.h"
//indicate conformity with protocol
@interface ParentName : UIViewController <ChildNameDelegate>
//In child .h file
//declare protocol
@protocol ChildNameDelegate
- (void) methodName:(dataType*) dataName;
@end
//declare delegate
@property (weak, nonatomic) id<ChildNameDelegate> delegate;
//In child .m file
//synthesize delegate
@synthesize delegate;
//use method
- (IBAction)actionName:(id)sender
{
[delegate methodName:assignedData];
}
文章来源: How to update the value of slider and switch when get back from presentModalViewController?