2015-11-20 2 views
1

У меня есть UICollectionView с включенным нижним колонтитулом раздела. Я создал пользовательский подкласс UICollectionReusableView называется LeafletFooterView и объявил некоторые IBOutlet s и IBAction s:Протоколы и делегаты, не работающие с UICollectionReusableView

- (IBAction)dropboxButton:(id)sender; 
- (IBAction)soundcloudButton:(id)sender; 

В моей UICollectionViewClass, у меня есть:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionReusableView *reusableview = nil; 

    if (kind == UICollectionElementKindSectionFooter) { 
     UICollectionReusableView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath]; 

     reusableview = footerview; 
    } 

    return reusableview; 
} 

В IBAction из LeafletFooterView класса, я просто пытается представить другой viewController:

- (IBAction)dropboxButton:(id)sender 
{ 
    VideoWebViewController *video = [[VideoWebViewController alloc] init]; 
    UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:video]; 

    [self presentViewController:navigation animated:YES completion:nil]; 

    [video setSelectedVideo:@"https://www.dropbox.com/"]; 
} 

Ошибка является:

No visible @interface for 'LeafletFooterView' declares the selector 'presentViewController:animated:completion'. 

Я попытался [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"www.dropbox.com"]]; в методе IBAction и, хотя в настоящее время нет никаких ошибок, при нажатии на него не открывается Safari с веб-сайтом. Метод определенно называется; a NSLog и Breakpoint доказать это.

Update

Так после этого не работал, я пытался пройти через процесс декларирования делегатов для этого, во многом таким же образом, этот вопрос делает: Present view controller from NSObject subclass.

Вот мой LeafletFooterView:

@class LeafletFooterView; 
@protocol FooterViewDelegate <NSObject> 
-(void)rowTapped; 
@end 
@interface LeafletFooterView : UICollectionReusableView 
@property (weak, nonatomic) IBOutlet UILabel *label; 
- (IBAction)dropboxButton:(id)sender; 
@property(nonatomic,assign)id<FooterViewDelegate> delegate; 

The LeafletFooterView.m is here: - (IBAction)dropboxButton:(id)sender 
{ 
    NSLog(@"Dropbox"); 
    [self.delegate rowTapped]; 
} 

Теперь в моем LeafletCollectionViewController, у меня есть:

- (void)rowTapped 
{ 
    NSLog(@"Is this getting called?"); 
    VideoWebViewController *video = [[VideoWebViewController alloc] init]; 
    UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:video]; 

    [self presentViewController:navigation animated:YES completion:nil]; 

    [video setSelectedVideo:@"https://www.dropbox.com/"]; 

} 

Когда я запускаю этот код, этот метод фактически никогда не вызывается. LeafletCollectionView настроен на использование FooterViewDelegate. В viewWillAppear из LeafletCollectionView, я попробовал следующее: не

LeafletFooterView *footer = [[LeafletFooterView alloc] init]; 
footer.delegate = self; 

Тем не менее метод rowTapped фактически никогда не вызывается.

Пользователь должен иметь возможность нажимать на UIButton в LeafletFooterView и представить его UIViewController. Как мне добиться этого? Любые рекомендации будут оценены.

ответ

1

Вам необходимо представить UINavigationController, где находится ваш dataSource. Поэтому, если вы попытаетесь удалить этот IBAction и вместо этого программно добавить метод, где ваш источник данных должен представить VideoWebViewController.

Затем в вашем методе viewForSupplementaryElementOfKind вы должны получить доступ к кнопке и запустить этот метод. Так, с верхней части моей головы (не использовали ObjC в то время):

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionReusableView *reusableview = nil; 

    if (kind == UICollectionElementKindSectionFooter) { 
     LeafletFooterView *footerview = (LeafletFooterView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath]; 
     [footerView.dropboxButton addTarget:self 
         action:@selector(dropboxTapped:) 
      forControlEvents:UIControlEventTouchUpInside]; 

     reusableview = footerview; 
    } 

    return reusableview; 
} 

-(void)dropboxTapped:(id)sender{ 
    // Present the controller here 
} 

Я надеюсь, что это помогает :)

EDIT: После обновления на ваш вопрос, я вижу, что вы блудодействуешь другой маршрут.Вам просто нужно установить делегат для footerView, как это:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionReusableView *reusableview = nil; 

    if (kind == UICollectionElementKindSectionFooter) { 
     LeafletFooterView *footerview = (LeafletFooterView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath]; 
     [footerView.dropboxButton addTarget:self 
            action:@selector(dropboxTapped:) 
          forControlEvents:UIControlEventTouchUpInside]; 
     footerView.delegate = self 
     reusableview = footerview; 
    } 

    return reusableview; 
} 

Кроме того, не забудьте бросить взгляд на LeafletFooterView, как я сделал в коде с помощью (LeafletFooterView *) я надеюсь, что работает :)

+0

Спасибо человеку - это очень полезно, и это имеет смысл. Я просто не слишком уверен в том, что «Так что если вы попытаетесь удалить этот IBAction и вместо этого программным образом добавите метод тому, кому ваш источник данных должен представить VideoWebViewController». Я не слишком уверен, что делать там – amitsbajaj

+0

@amitsbajaj уверен, удалите IBAction (в построителе интерфейса, где вы нажимаете кнопку, затем выходы, затем крест для действия), затем попробуйте код выше – Daven

+0

Nice! Спасибо, человек, который работал как шарм! – amitsbajaj

Смежные вопросы