【发布时间】:2014-01-07 02:52:03
【问题描述】:
所以我开始涉足 iOS 开发的 Objective-C 编程。我有一个正在开发的小应用程序,没什么特别的,但可以帮助我掌握一些技巧。我遇到的问题如下:
目前,我有两节课。第一个是
ViewController
第二个是我自己创造的,叫做
UserDecision
View 控制器显示屏幕上的内容,UserDecisions 当前从屏幕上按下的按钮获取信息,并在使用我的模型类时对其执行适当的逻辑。我的问题是,如果发生某些事件,我在 UserDecision 中有一个更新 UI 方法,它需要更新 ViewController 中的按钮属性(文本、可见性等)。因此,我无法使用 ViewController 的实例,因为我无法访问屏幕上的按钮。所以为此我创建了一个委托系统:
@protocol updateUIDelegate <NSObject>
-(void)hideAll;
-(void)makeBackVisible;
-(void)updateOutput:(NSString *)output;
-(void)updateChoices:(NSString *)choices;
-(void)updateTrueButton:(NSString *)trueString;
-(void)updateFalseButton:(NSString *)falseString;
-(void)removeChoiceFromArray;
@end
上面的协议是在 UserDecision.h 中定义的,然后我将我的 ViewController 分配为我的委托:
@interface ViewController : UIViewController <updateUIDelegate>;
然后我在 ViewController.m 中清除上述方法:
#pragma - updateUIDelegates -
//Called when the last screen is displayed
-(void)hideAll{
[_trueButton setHidden:true];
[_falseButton setHidden:true];
[_choicesText setHidden:true];
[_backButton setHidden:true];
[_resetButton setHidden:false];
}
//Makes back button visible
-(void)makeBackVisible{
[_backButton setHidden:false];
}
//Updates the text on the false button
-(void)updateFalseButton:(NSString *)falseString{
[_falseButton setTitle:falseString forState:UIControlStateNormal];
}
//Updates the text on the true button
-(void)updateTrueButton:(NSString *)trueString{
[_trueButton setTitle:trueString forState:UIControlStateNormal];
}
//Updates the output text box
-(void)updateOutput:(NSString *)output{
[_outputText setText:output];
}
//Updates the choices textbox
-(void)updateChoices:(NSString *)choices{
if(!choicesArray){
choicesArray = [[NSMutableArray alloc] initWithCapacity:4];
}
//If this is the first button press, add string to array and display
if([_choicesText.text isEqualToString:@""]){
[choicesArray addObject:choices];
_choicesText.text = [NSString stringWithFormat:@"%@", choices];
}
//Otherwise, add the new string to the array, and print the array
//using a comma as a way to concatinate the string and get rid of
//the ugly look of printing out an array.
else{
[choicesArray addObject:choices];
[_choicesText setText:[NSString stringWithFormat:@"%@",[choicesArray componentsJoinedByString:@", "]]];
}
}
//Removes the last choice from the array
-(void)removeChoiceFromArray{
[choicesArray removeLastObject];
[_choicesText setText:[NSString stringWithFormat:@"%@", [choicesArray componentsJoinedByString:@","]]];
}
这允许我在需要时通过将它们作为消息发送到我的UserDecision 类中的self.delegate 来调用这些方法。
这是我目前的设置。我的问题已经变成我想创建一个在最后弹出的模态序列视图(在用户按下按钮以调出视图之后),然后可以将其关闭。我的问题是,从我在网上所做的阅读和研究来看,这种观点只能通过授权来驳回,除非我想让事情变得令人讨厌。现在,我试图在我的类中实现这些信息,但后来我读到一个类只能是另一个类的委托。而且由于我的ViewController(这是我的主窗口)已经是我的UserDecision 类的代表,我不能让它成为我创建的新视图的代表,因此不能关闭视图。所以,我在这里寻求您的帮助。我该如何解决这个问题?
另外,关于我的更多代码,如果你想看看,这里是我的 gitHub 的链接:https://github.com/Aghassi/Xcode/tree/master/Bubble%20Tea%20Choice/Bubble%20Tea%20Choice
【问题讨论】:
标签: ios iphone objective-c uiviewcontroller delegates