2012-10-24 15 views
0

我寫了一個不錯的圖庫視圖控制器.h .m和.xib,它們可以很好地用於我的目的。點擊一個以編程方式創建的按鈕,並加載圖像,播放電影或查看PDF或網站 - 而在現有的uinavigationcontroller。我想改變它,所以我可以在代碼中添加xib的內容 - 而不使用nib文件。這樣它會更有用(我認爲)。重構iOS ViewController無需使用筆尖即可工作

問題是.m中的函數引用,例如 - [self presentMoviePlayerViewControllerAnimated:YES]等不起作用。我嘗試在這個新的.h和.m中創建rootviewcontroller的屬性,並用myController(屬性名稱)替換self。但我的視圖控制器代碼依賴現有的uinavigation來推動新的內容或類似的東西。我怎樣才能刪除/調整這些引用自我或依賴uinavigationcontrollers,所以它會像當它有一個視圖控制器的筆尖一樣工作?

編輯:添加代碼如下。在筆尖中只有一個名爲uis_thumbScrollView的uiscrollView。我想通過簡單地調用像添加此隨地:

[self.view addSubview:[[ebThumbScroller alloc] initWithFrame:CGRectMake(0, 0, 1024, 733)]]; 

大家的言論提醒了我,這將是擺在了UIView的RootViewController的中存在,在上面。也許這就是爲什麼我能聽到電影播放 - 但沒有看到它。

注意:代碼在uiscrollview中創建一系列uiviews按鈕。 .H #進口 #進口 「ebAppDelegate.h」 #進口 「的MediaPlayer/MediaPlayer.h」

@interface HomeGalleryViewController : UIViewController <UIScrollViewDelegate, UIGestureRecognizerDelegate, UIDocumentInteractionControllerDelegate> { 

    BOOL pageControlBeingUsed; 
    int buttonCount; 

    CGFloat   _minimumColumnGap; 
    UIEdgeInsets _contentInsets; 
    NSInteger  _colCount; 
    NSInteger  _rowCount; 
    CGFloat   _rowGap; 
    CGFloat   _colGap; 
    UIEdgeInsets _effectiveInsets; 
    //int iGalleryThumbs; 
    //int iPlanThumbs; 
    int iTotalButtons; 
    ebAppDelegate *ebappdelegate; 
    ebGalleryItem *ebgalleryItem; 
    NSDictionary *gallDict; 
    NSArray *gallerySections; 
    NSArray *galleryArray; 
    NSMutableArray *nsm_gallArray; 
    UIDocumentInteractionController *controller; 
} 

//@property (nonatomic, retain) IBOutlet UIButton *bItem; 
@property (nonatomic, retain) NSString *galleryNameString; 
@property (nonatomic, retain) IBOutlet UIScrollView* scrollView; 
@property (retain, nonatomic) NSMutableArray *arr_Views; 
@property (strong, nonatomic) IBOutlet UIScrollView* uis_thumbScrollView; 
@property (strong, nonatomic) IBOutlet UIPageControl* uis_pageControl; 
@property (strong, nonatomic) IBOutlet UIView *uiv_thumbView; 
@property (strong, nonatomic) MPMoviePlayerController *player; 
@property (strong, nonatomic) MPMoviePlayerViewController *playerViewController; 


- (IBAction)changePage; 
- (IBAction) clickOpen:(id)sender; 
- (void)playMovie:(NSString*)movieName; 
- (void)movieFinishedCallback:(NSNotification*)_notification; 

@end 

.M

#import "HomeGalleryViewController.h" 
#import "ebAppDelegate.h" 
#import "GalleryImagesViewController.h" 
#import "Gallery.h" 
#import "GalleryThumbnailsViewController.h" 
#import "GalleriesListViewController.h" 
#import <QuartzCore/CoreAnimation.h> 
#import "ebGalleryItem.h" 
#import "WebViewController.h" 

@implementation HomeGalleryViewController 
// buttons 
#define hGutter 17 
#define vGutter 13 
#define btnSize 130 
#define topSpace 50 
#define leftMargin 100 

@synthesize uiv_thumbView; 

@synthesize uiv_gallCat0, uiv_gallCat1, uiv_gallCat2,uiv_gallCat3, uiv_gallCat4, uiv_gallCat5,uiv_gallCat6; 
@synthesize uis_thumbScrollView, uis_pageControl; 

@synthesize galleryNameString,scrollView,arr_Views; 
@synthesize player, playerViewController; 

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad { 

    [super viewDidLoad];  

    ebappdelegate = (ebAppDelegate *)[[UIApplication sharedApplication] delegate]; 
    arr_Views = [[NSMutableArray alloc] init]; 

    self.scrollView.contentSize = CGSizeMake(1024, 1005); 

    // nsarray of dictionaries (galleries) 
    gallerySections = ebappdelegate.arr_galleryData; 
    NSLog(@"gallerySections count:%i",[gallerySections count]); 
    nsm_gallArray = [NSMutableArray arrayWithCapacity:1]; 

    [self layoutGalleryThumbs]; 
} 

#pragma mark 
#pragma mark Layout Gallery Thumbs 

-(void)layoutGalleryThumbs { 

    NSUInteger numGallSections = [gallerySections count]; 
    NSLog(@"gallerySections data:%@",gallerySections); 
    NSLog(@"numGallSections count:%i",numGallSections); 

    // Window bounds. 
    CGRect bounds = CGRectMake(0, 0, 1024, 215); 

    for (int i=0; i<numGallSections; i++) { 

     // Create a view and add it to the window. 
     UIView* vview = [[UIView alloc] initWithFrame: CGRectMake(0, bounds.size.height*i-1, bounds.size.width, bounds.size.height)]; 
     [vview setBackgroundColor: [UIColor whiteColor]]; 
     [vview setTag:i]; 
     //vview.backgroundColor = (UIColor (i % 2 == 0 ? cyanColor : whiteColor]; 
     vview.backgroundColor = (i % 2 == 0)? [UIColor lightGrayColor] : [UIColor whiteColor]; 

     [arr_Views addObject:vview]; 

     // add line below at bottom 
     UIView* lineView = [[UIView alloc] initWithFrame: CGRectMake(280, bounds.size.height, 700, 2)]; 
     [lineView setBackgroundColor: [UIColor grayColor]]; 
     lineView.alpha = 0.5; 
     [vview addSubview:lineView]; 

     [uis_thumbScrollView addSubview: vview]; 

     NSLog(@"start===============i:%i",i); 

     // grab a gallery 
     gallDict = [gallerySections objectAtIndex:i];  // grab dict 
     galleryArray = [gallDict objectForKey:@"gallSectionData"]; // grab array from dict 
     NSLog(@"galleryArray:%@",[galleryArray description]); 
     NSString *secTitle = [gallDict objectForKey:@"gallSectionName"]; 

     iTotalButtons = [galleryArray count]; 
     NSLog(@"iTotalButtons count:%i",iTotalButtons); 

     _minimumColumnGap = 5; 

     _colCount = floorf((uis_thumbScrollView.bounds.size.width - _contentInsets.left - _contentInsets.right)/btnSize); 

     while (1) { 
      _colGap = (uis_thumbScrollView.bounds.size.width - _contentInsets.left - _contentInsets.right - btnSize * _colCount)/(_colCount + 1); 
      if (_colGap >= _minimumColumnGap) 
       break; 
      --_colCount; 
     }; 

     _rowCount = (iTotalButtons + _colCount - 1)/_colCount; 
     _rowGap = _colGap; 

     _effectiveInsets = UIEdgeInsetsMake(_contentInsets.top + _rowGap, 
              _contentInsets.left + _colGap, 
              _contentInsets.bottom + _rowGap, 
              _contentInsets.right + _colGap); 

     NSLog(@"row count:%i",_rowCount); 
     NSLog(@"col count:%i",_colCount); 

     buttonCount=0; 

     for (int e=0; e<iTotalButtons; e++) { 
      NSLog(@"e:%i",e); 

      ebgalleryItem = [galleryArray objectAtIndex:e]; 
      UIImage *thumbImg = [UIImage imageNamed:ebgalleryItem.gallThumb]; 

      UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom]; 

      CGRect frame = CGRectMake (btnSize*e+leftMargin, topSpace, 
             btnSize-hGutter, btnSize-vGutter); 
      [button setFrame: frame]; 
      NSLog(@"added button"); 

      //[button setBackgroundImage:thumbImg forState:UIControlStateNormal]; 
      [button setImage:thumbImg forState:UIControlStateNormal]; 
      [button setTitle:ebgalleryItem.gallName forState:UIControlStateNormal]; 
      NSLog(@"%@",button.titleLabel.text); 

      [button addTarget: NULL action:@selector(clickOpen:) forControlEvents:UIControlEventTouchUpInside]; 
      UILongPressGestureRecognizer *tapAndHold = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longclickOpen:)]; 
      [tapAndHold setMinimumPressDuration:0.33]; 
      [button addGestureRecognizer:tapAndHold]; 
      [button setTag:e]; 
      //[button setTag:i*_colCount+e]; 

      NSLog(@" button tag=%i", button.tag); 

      button.alpha=1.0; 
      [[arr_Views objectAtIndex:i] addSubview:button]; 
      NSLog(@"middle====i:%i",i); 

      // caption label 
      CGRect labelFrame = CGRectMake(btnSize*e+leftMargin, 125, 
              btnSize-hGutter, btnSize-vGutter); 
      UILabel* label = [[UILabel alloc] initWithFrame: labelFrame]; 
      [label setFont:[UIFont fontWithName:@"Arial" size:14]]; 
      label.numberOfLines = 0; 
      [label setText:ebgalleryItem.gallCaption]; 
      [label setTextColor: [UIColor blackColor]]; 
      [label setTextAlignment:UITextAlignmentCenter]; 
      [label setBackgroundColor:[UIColor clearColor]]; 
      [[arr_Views objectAtIndex:i] addSubview: label]; 
      NSLog(@"middle2====i:%i",i); 

      buttonCount++; 
     } 

     // Section Title label 
     CGRect titleLabelFrame = CGRectMake(btnSize,0,250,50); 
     UILabel* titlelabel = [[UILabel alloc] initWithFrame: titleLabelFrame]; 
     [titlelabel setFont:[UIFont fontWithName:@"Arial" size:16]]; 
     [titlelabel setText:secTitle]; 
     [titlelabel setTextColor: [UIColor blackColor]]; 
     [titlelabel setTextAlignment:UITextAlignmentLeft]; 
     [titlelabel setBackgroundColor:[UIColor clearColor]]; 
     [[arr_Views objectAtIndex:i] addSubview: titlelabel]; 
     NSLog(@"end====i:%i",i); 


     CGFloat scrollViewHeight = 0.0f; 
     for (UIView* view in self.uis_thumbScrollView.subviews) 
     { 
      if (!view.hidden) 
      { 
       CGFloat y = view.frame.origin.y; 
       CGFloat h = view.frame.size.height; 
       if (y + h > scrollViewHeight) 
       { 
        scrollViewHeight = h + y; 
       } 
      } 
     } 


     [self.uis_thumbScrollView setContentSize:(CGSizeMake(self.uis_thumbScrollView.frame.size.width, scrollViewHeight+74))]; //74 is space from top in IB of scroll 
     } 
    uiv_thumbView.alpha = 1.0; 
} 


#pragma mark Scrollview 

- (void)scrollViewDidScroll:(UIScrollView *)sender { 
    // Update the page when more than 50% of the previous/next page is visible 
    CGFloat pageWidth = self.uis_thumbScrollView.frame.size.width; 
    int page = floor((self.uis_thumbScrollView.contentOffset.x - pageWidth/2)/pageWidth) + 1; 
    self.uis_pageControl.currentPage = page; 

    // nslogs zoomsacle/bounds 
    CGRect visibleRect; 
    visibleRect.origin = uis_thumbScrollView.contentOffset; 
    visibleRect.size = uis_thumbScrollView.bounds.size; 

    float theScale = 1.0/[uis_thumbScrollView zoomScale]; 
    visibleRect.origin.x *= theScale; 
    visibleRect.origin.y *= theScale; 
    visibleRect.size.width *= theScale; 
    visibleRect.size.height *= theScale; 

    NSLog(@"Visible rect: %@", NSStringFromCGRect(visibleRect)); 
} 

- (IBAction)changePage { 
    // update the scroll view to the appropriate page 
    CGRect frame; 
    frame.origin.x = self.uis_thumbScrollView.frame.size.width * self.uis_pageControl.currentPage; 
    frame.origin.y = 0; 
    frame.size = self.uis_thumbScrollView.frame.size; 
    [self.uis_thumbScrollView scrollRectToVisible:frame animated:YES]; 
} 

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { 
    pageControlBeingUsed = NO; 
} 

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { 
    pageControlBeingUsed = NO; 
} 

//=================================================================== 
// Override to allow orientations other than the default portrait orientation. 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft | interfaceOrientation == UIInterfaceOrientationLandscapeRight); 
} 

- (void)didReceiveMemoryWarning { 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

    // Release any cached data, images, etc that aren't in use. 
} 

- (void)viewDidUnload { 
    [self setUiv_thumbView:nil]; 
} 

- (void)viewDidDisappear:(BOOL)animated { 
} 

- (void)viewWillAppear:(BOOL)animated { 
    [UIApplication sharedApplication].statusBarHidden = YES; 
    self.view.frame = [UIScreen mainScreen].applicationFrame; 
    CGRect frame = self.navigationController.navigationBar.frame; 
    frame.origin.y = 0; 
    self.navigationController.navigationBar.frame = frame; 
    [self.navigationController setNavigationBarHidden:YES animated:animated]; 
    self.navigationController.navigationBar.translucent = YES; 
} 

- (void)viewWillDisappear:(BOOL)animated { 
    [UIApplication sharedApplication].statusBarHidden = NO; 
    CGRect frame = self.navigationController.navigationBar.frame; 
    frame.origin.y = 20.0; 
    self.navigationController.navigationBar.frame = frame; 
} 

- (void)viewDidAppear:(BOOL)animated { 
    [[UIApplication sharedApplication] setStatusBarHidden:YES]; 
    [self.navigationController setNavigationBarHidden:YES animated:animated]; 
    [self.navigationController setToolbarHidden:YES animated:YES]; 
    [super viewDidAppear:animated]; 
} 

//======================================================================  
-(IBAction)clickOpen:(id)sender { 

    UIButton *tmpBtn = (UIButton*)sender; 
    NSLog(@"sender tag: %i", [sender tag]); 

    int superviewTag = [sender superview].tag; 
    NSLog(@"sender superview tag: %i", superviewTag); 

    gallDict = [gallerySections objectAtIndex:superviewTag];  // grab dict 
    galleryArray = [gallDict objectForKey:@"gallSectionData"];  // grab array from dict 

    tmpBtn.alpha = 0.6; 

    ebgalleryItem = [galleryArray objectAtIndex:[sender tag]]; 

    NSLog(@"%@",ebgalleryItem.gallType); 
    NSLog(@"%@",ebgalleryItem.gallName); 

    NSLog(@"gallDict %@",gallDict); 

    if ([ebgalleryItem.gallType isEqualToString:@"movie"]) { 

     [self playMovie:ebgalleryItem.gallFilm]; 

    } else if ([ebgalleryItem.gallType isEqualToString:@"image"]) { 

     [self imageViewer:sender]; 

    } else if ([ebgalleryItem.gallType isEqualToString:@"pdf"]) { 

     [self viewPDF:ebgalleryItem.gallName]; 

    } else if ([ebgalleryItem.gallType isEqualToString:@"web"]) { 

     [self openWeb:ebgalleryItem.gallName]; 
    } 
} 

#pragma mark 
#pragma mark Open Websites 

- (IBAction)openWeb:(NSString*)thisWEB { 

    WebViewController *webViewController = [[WebViewController alloc] 
              initWithNibName:@"WebViewController" 
              bundle:nil]; 
    [webViewController socialButton:thisWEB]; 
    webViewController.title = thisWEB; 
    [self presentModalViewController:webViewController animated:YES]; 
} 

#pragma mark 
#pragma mark Image Viewer 

-(void)imageViewer:(id)sender { 

    UIButton *tmpBtn = (UIButton*)sender; 

    galleryNameString = tmpBtn.titleLabel.text; 
    tmpBtn.alpha = 0.6; 

    GalleryImagesViewController *vc = [[GalleryImagesViewController alloc] initWithGallery:[Gallery galleryNamed:galleryNameString]]; 
    [vc goToPageAtIndex:0 animated:NO]; 

    CATransition* transition = [CATransition animation]; 
    transition.duration = 0.33; 
    transition.type = kCATransitionFade; 
    transition.subtype = kCATransitionFromTop; 

    [self.navigationController.view.layer 
    addAnimation:transition forKey:kCATransition]; 
    [self.navigationController pushViewController:vc animated:NO]; 
} 

#pragma mark 
#pragma mark PDF Viewer 

-(void)viewPDF:(NSString*)thisPDF { 
    NSString *fileToOpen = [[NSBundle mainBundle] pathForResource:thisPDF ofType:@"pdf"]; 
    NSURL *url = [NSURL fileURLWithPath:fileToOpen]; 

    NSLog(@"%@",fileToOpen); 
    controller = [UIDocumentInteractionController interactionControllerWithURL:url]; 
    [self previewDocumentWithURL:url]; 
} 


- (IBAction) clickClose:(id)sender { 
    [self dismissModalViewControllerAnimated:YES]; 
} 

- (void)previewDocumentWithURL:(NSURL*)url 
{ 
    UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:url]; 
    preview.delegate = self; 
    [preview presentPreviewAnimated:YES]; 
} 

//======================================================================  
- (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller{ 
} 

//=================================================================== 
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller 
{ 
    return self; 
} 

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller 
{ 
    return self.view; 
} 

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller 
{ 
    return self.view.frame; 
} 


-(IBAction)longclickOpen:(UILongPressGestureRecognizer*)gesture { 

    if (gesture.state == UIGestureRecognizerStateBegan) { 

     [self.navigationController setNavigationBarHidden:NO]; 

     ebAppDelegate *appDelegate = (ebAppDelegate *)[[UIApplication sharedApplication] delegate]; 
     appDelegate.isFromLongPress=YES; 

     //NSUInteger i = [gesture.view tag]; 

     //galleryNameString = [appDelegate.arr_galleryData objectAtIndex:i]; 

     NSLog(@"load %@",galleryNameString); 

     UIButton *btn = (UIButton*)gesture.view; 

     galleryNameString = btn.titleLabel.text;  btn.alpha = 0.6; 

     //NSLog(@"Long Press"); 
     //NSLog(@"llongclickOpen"); 
     UIViewController *vc = [[GalleryThumbnailsViewController alloc] initWithGallery:[Gallery galleryNamed:galleryNameString]]; 
     CATransition* transition = [CATransition animation]; 
     transition.duration = 0.33; 
     transition.type = kCATransitionFade; 
     transition.subtype = kCATransitionFromTop; 

     [self.navigationController.view.layer 
     addAnimation:transition forKey:kCATransition]; 
     [self.navigationController pushViewController:vc animated:NO]; 
    } 
} 


-(void)playMovie:(NSString*)movieName { 

    NSString *url = [[NSBundle mainBundle] 
        pathForResource:movieName 
        ofType:@"m4v"]; 

    NSLog(@"%@",movieName); 

    playerViewController = [[MPMoviePlayerViewController alloc] 
                 initWithContentURL:[NSURL fileURLWithPath:url]]; 

    [[NSNotificationCenter defaultCenter] removeObserver:playerViewController 
                name:MPMoviePlayerPlaybackDidFinishNotification 
                object:playerViewController.moviePlayer]; 

    // Register this class as an observer instead 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(movieFinishedCallback:) 
               name:MPMoviePlayerPlaybackDidFinishNotification 
               object:playerViewController.moviePlayer]; 

    [self.view insertSubview:playerViewController.view atIndex:50]; 

    //---play movie--- 
    player = [playerViewController moviePlayer]; 
    player.controlStyle = MPMovieControlStyleFullscreen; 
    player.repeatMode=MPMovieRepeatModeOne; 

    [self presentMoviePlayerViewControllerAnimated:playerViewController]; 
    [[UIApplication sharedApplication] setStatusBarHidden:YES]; 

    [super viewDidLoad]; 
} 

- (void)movieFinishedCallback:(NSNotification*)aNotification { 
    // Obtain the reason why the movie playback finished 
    NSNumber *finishReason = [[aNotification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]; 

    // Dismiss the view controller ONLY when the reason is not "playback ended" 
    if ([finishReason intValue] != MPMovieFinishReasonPlaybackEnded) 
    { 
     MPMoviePlayerController *moviePlayer = [aNotification object]; 

     // Remove this class from the observers 
     [[NSNotificationCenter defaultCenter] removeObserver:self 
                 name:MPMoviePlayerPlaybackDidFinishNotification 
                 object:moviePlayer]; 
     // Dismiss the view controller 
     [self dismissModalViewControllerAnimated:YES]; 
    } 
} 


@end 
+0

我認爲你需要更具體的什麼是不工作,也許提供一些代碼。一般來說,完全可以用代碼替換在XIB中完成的所有設置。 – Tobi

+0

.xib將提供內容的自動實例化和設置。所以,如果一個方法或某些東西不能正常工作,那麼我的猜測是你沒有正確實例化並初始化了xib中免費提供的所有東西。聽起來就像你在代碼中所做的事情比可以容易地展示的更多。我的建議是通過並確保一切都在那裏,通過設置背景顏色驗證視圖(除非以其他方式顯而易見),直到您擁有過去的所有視圖和導航爲止。然後你可以看看更具體的問題。 – Matt

+0

好點。雖然一切都很好 - 滾動不會滾動,當然打開內容的功能也不會顯示。 – malaki1974

回答

1

如果你唯一的問題是不工作[self presentMoviePlayerViewControllerAnimated:YES]方法,問題是presentMoviePlayerViewControllerAnimated:需要實際的moviePlayerViewController作爲參數而不是布爾值。 (假設你指的是UIViewController類別的這種方法)UIViewController MediaPlayer Additions Reference

所以如果你用presentMoviePlayerViewControllerAnimated:self.moviePlayerVC代替它,它應該按預期工作。

+0

我會試試這個。 – malaki1974

0

我不知道我理解你的問題,但如果您需要將控制器換到一些UINavigationController的,你可以做這樣的:

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:myController]; 
    navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical; 
    navController.navigationBar.barStyle = UIBarStyleBlack; 
    [self presentViewController:navController animated:YES completion:^{ 
     // 
    }]; 

後Ø n任何子控制器都將具有導航層次結構。

+0

感謝您的提示 - 也許我需要在上述功能中包含上述功能(pdf,play movie)。 – malaki1974