如何手动初始化自定义UIView

问题描述:

这可能是一个简单的问题,但我发现自己卡住了。我试图扩展UIView并从另一个控制器初始化它,但发现我的自定义UIView初始化方法没有调用。我如何初始化我的自定义UIView?如何手动初始化自定义UIView

// BookView.h 
@interface BookView : UIView { 
} 

//BookView.m 
@implementation BookView 
- (void) initialize{ 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Alert" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; 
    [alert show]; 
    [alert release]; 
} 
@end 

//BookViewController.m 
-(void)viewDidLoad{ 
    BookView *bookView = [(BookView*)[BookView alloc] initWithTest:[[UIScreen mainScreen] bounds]]; 
} 
+0

尝试[bookView initialize]; – visakh7 2011-05-30 06:04:53

试试这个,

BookView *bookView =[[BookView alloc] init]; 
bookView.frame=self.view.frame; 
[self.view addSubView:bookView]; 
[bookView release]; 
+0

如果你不释放'bookView',这会导致内存泄漏。 – fuzz 2011-05-30 05:56:44

+0

感谢您的回复。但不工作。 – TonyTakeshi 2011-05-30 05:58:10

+0

更改你的 - (void)初始化为 - (void)init然后它会工作 – Navaneethan 2011-05-30 06:00:27

NSArray *nibViews = [[NSBundle mainBundle] loadNibNamed:@"BookView" owner:self options:nil]; 
self.yourBookView = [nibViews objectAtIndex:0]; 
+0

谢谢你的回复,但我没有使用任何nib文件。 – TonyTakeshi 2011-05-30 05:56:57

//BookView.m 
@implementation BookView 
- (void) init { // changed from (void)initialize {} 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Alert" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; 
    [alert show]; 
    [alert release]; 
} 

..和再申请@Navaneethan初始化您BookView的。