Jer*_*emy 1 class nib nsobject ios
我有一个常见的方法,导致出现"联系我们"(UIActionSheet)消息.因为我在多个类中使用相同的代码,我试图移动到它自己的类(我使用NSObject类类型).
问题是,如何让UIActionSheet出现在需要它的类的NIB中?
我在NSObject类中使用此代码:
UIActionSheet *msg = [[UIActionSheet alloc]
initWithTitle:@"Consultation Request"
delegate:self
cancelButtonTitle:@"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:@"Email",@"Text",@"Office Phone", nil];
msg.actionSheetStyle = UIActionSheetStyleBlackOpaque;
[msg showInView:self.view];
Run Code Online (Sandbox Code Playgroud)
显然最后一行是错误的,因为"视图"是原始类的NIB.
有3个选项.
您可以使用属性来告诉您NSObject应该在哪里显示您的操作表:
///// MyObject.h
@property (nonatomic, strong /* or rerain if not ARC */) UIView *viewForActionSheet;
//// MyObject.m
@synthesize viewForActionSheet;
...
[msg showInView:self.viewForActionSheet];
//// MyViewController.m
MyObject *obj = [[MyObject alloc] init];
obj.viewForActionSheet = self.view;
[obj presentMyActionSheet];
Run Code Online (Sandbox Code Playgroud)
这是使用obj-c协议(aka委托)的更高级方法
//// MyObject.h
@protocol MyObjectDelegate <NSObject>
@required
- (UIView *)viewForActionSheet;
@end;
@interface MyObject : NSObject
...
@property (nonatomic, unsafe_unretained /* or assign if not ARC */) id <MyObjectDelegate> delegate;
@end
//// MyObject.m
@synthesize delegate;
...
[msg showInView:self.delegate.viewForActionSheet];
//// MyViewController.m
- (UIView *)viewForActionSheet {
return self.view;
}
Run Code Online (Sandbox Code Playgroud)
最简单的方法,但不是最安全的方式
//// MyObject.m
[msg showInView:[[UIApplication sharedApplication] keyWindow]];
Run Code Online (Sandbox Code Playgroud)