从presentModalViewController返回时如何更新滑块和切换的值?

时间:2012-07-20 13:13:14

标签: iphone objective-c ios xcode

我有一些帐户,他们有一些设置属性。作为设置,值为UISlider,值为UISwitch。当我运行应用程序它工作正常我可以显示NSUserDefaults的最后一个值,因为viewDidLoad方法工作。我的应用程序有一个标签栏控制器。因此,当我切换标签时,它也能正常工作,因为我可以获得开关和滑块的值,并在viewWillAppear方法中更新它们。但在我的设置开关中,我提供了一个视图,其中有用户列表,因此用户可以选择任何帐户。当我从呈现的视图返回时,我无法更新开关和滑块的值。我需要一个触发器方法来更新它们的值。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:0)

我刚才写过这篇文章,基本上只是把它粘贴到所有这些问题中。顺便说一句,如果有人提出的建议可以让我更容易理解/更好,我很乐意听到它们。

您可以使用委托在类之间传递信息;这对于在使用方法时要传递信息的情况特别有用。

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];
}

答案 1 :(得分:0)

是的,这是3种苹果方式:

1) Delegation
2) NSNotificationCenter
3) KVO

然而,对于您的特定情况的模态视图,委托模式是Apple推荐的模式,也是我推荐的模式。

它需要比其他两个选项更多的编码。

首先,您必须在模拟呈现的视图中声明协议:

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];

并相应更新。

希望有所帮助。