2015-05-26 3 views
0

У меня есть файлы DiscoverViewController.h и .m, которые имеют функцию, которая перемещает виды мест для обнаружения. Я хочу повторно использовать это представление в контроллерах вывода. Код для DicoverViewController.m с ниже:Создание подкласса для UIView для повторного использования

for (PFObject *views in objects) 
{ 
    // Get the discoverr view setup 
    CGRect frame = CGRectMake(5.0, _viewStart, 310.0, viewHeight); 

    DiscoverView *parent = [[DiscoverView alloc] init]; 

    [parent buildDiscoverViewWithFrame:frame andObjects:replies]; 
    // UIView *parent = [[UIView alloc] initWithFrame:CGRectMake(5.0, _viewStart, 310.0, viewHeight)]; 
    parent.backgroundColor = [UIColor whiteColor]; 
    // parent.layer.cornerRadius = 2.0; 
    parent.layer.borderColor = [UIColor regularColor].CGColor; 
    parent.layer.borderWidth = 1.0f; 
    parent.tag = 1000 + _step; 

    // Add the label counter 
    // Add discover id for testing (is unique id) 
    UILabel *placeholder = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 10.0, 310.0, 12.0)]; 
    placeholder.backgroundColor = [UIColor clearColor]; 
    placeholder.textAlignment = NSTextAlignmentCenter; 
    placeholder.textColor = [UIColor bestTextColor]; 
    placeholder.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:(12.0)]; 
    placeholder.Text = [NSString stringWithFormat:@"%@", views.objectId]; 

    [parent addSubview:placeholder]; 

    // Increase size of content view 
    CGRect newContentView = _contentView.frame; 

    newContentView.size.width = _contentView.frame.size.width; 
    newContentView.size.height = _contentView.frame.size.height + bestHeight; 

    [_contentView setFrame:newContentView]; 

    [_contentView addSubview:parent]; 

    scrollView.contentSize = _contentView.frame.size; 

    // Adjust the postions 
    _viewStart = _viewStart + viewHeight - 1.0; 
    _step = _step + 1; 
}     

класс называется DiscoverView.h

#import <UIKit/UIKit.h> 
#import <Parse/Parse.h> 

@interface DiscoverView : UIView 

- (UIView *) buildDiscoverViewWithFrame:(CGRect) frame andObjects:(PFObject *) objects; 

@end 

Файл реализации DiscoverView.m:

- (UIView *) buildDiscoverViewWithFrame:(CGRect) frame andObjects:(PFObject *) objects 
{ 
    UIView *discover = [[UIView alloc] initWithFrame:frame]; 

    _photoObject = objects.objectId; 

    //Add a gesture to dismiss keyboard on tap 
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(discoverTapPressed)]; 

    [discover addGestureRecognizer:tap]; 

    return discover; 
} 

- (void) discoverTapPressed 
{ 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"The id is:" 
               message:_photoObject 
               delegate:nil 
             cancelButtonTitle:@"OK" 
             otherButtonTitles:nil]; 
    [alert show]; 
} 

Как-то это работает неправильно. Рамка не будет отображаться в правом пространстве, а крана не работает вообще. Мне нужно изменить его как ссылку на класс или экземпляр? Как повторно использовать этот класс (DiscoverView) и заставить его работать правильно?

Спасибо.

+0

Почему вы не используете UITableView или UICollectionView? любая конкретная причина создания ручного бесконечного прокрутки? – abhishekkharwar

+0

Посмотрите мой комментарий ниже об этом (в значительной степени в представлении таблицы было 90 процентов работы, но последние 10 процентов пользовательского интерфейса, который я хотел для моего приложения, были жесткими). Но я использую представления таблиц и коллекции в другом месте, где вся страница сама представляет собой представление коллекции или таблицы. – cdub

+0

вы можете опубликовать снимок экрана UI? – abhishekkharwar

ответ

1

Ваша идея очень хорошо, и я думаю, что вы на правильном пути ... ты только что сделал несколько ошибок:

- (UIView *)buildDiscoverViewWithFrame:(CGRect) frame andObjects:(PFObject *) objects 
{ 
    //Your method name is buildDiscoverView, but you are making a view 
    //that is not a DiscoverView class. 
    UIView *discover = [[UIView alloc] initWithFrame:frame]; 

    //Tap gesture stuff... 

    return discover; 
} 

И:

DiscoverView *parent = [[DiscoverView alloc] init]; 

//parent will not contain an attached tap gesture, but the view 
//returned from its method does... 
[parent buildDiscoverViewWithFrame:frame andObjects:replies]; 

//Ex: 
//UIView *viewWithYourTapGesture = [parent buildDiscoverViewWithFrame:frame andObjects:replies]; 

Я вполне уверен, что это не то, что вы действительно хотите. Я думаю, вы пытаетесь создать экземпляр DiscoveryView, а не правильно? Вы можете сделать это следующим образом:

На вашем DiscoveryView.m

- (id)initWithFrame:(CGRect)frame andObjects:(PFObject *)objects { 

    //You can call initWithFrame: method here as our base constructor 
    self = [super initWithFrame:frame]; 

    if (self) { 

     //Add tap gesture here 
     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(discoverTapPressed)]; 
     [self addGestureRecognizer:tap]; 

     //and maybe do some other stuff as changing the background color 
     //or making the border stuff that you are doing outside... 
    } 

    return self; 
} 

Теперь вы можете инициализировать экземпляр, как показано ниже:

На вашем DiscoverViewController.m

DiscoverView *parent = [[DiscoverView alloc] initWithFrame:frame andObjects:replies]; 

//If you do this on init, you don't need this anymore... 
//parent.backgroundColor = [UIColor whiteColor]; 
//parent.layer.cornerRadius = 2.0; 
//parent.layer.borderColor = [UIColor regularColor].CGColor; 
//parent.layer.borderWidth = 1.0f; 

FYI: Я также рекомендую вам ознакомиться с новой функцией IBDesignable, которая позволяют визуализировать результаты непосредственно из раскадровки (но это не то, что вы просите на эту тему.)

Update:

Как @abhishekkharwar сказал, есть много других способов сделать это лучше, используя UICollectionView или UITableView, но вам нужно решить, что лучше подходит для ваших приложений. Просто попробуйте НЕ заново изобрести колесо.

+0

Да У меня есть коллекции просмотров и таблиц в приложении. Это было просто для этих страниц/контроллеров ceratin, что на странице существует несколько разных типов пользовательских интерфейсов, которые сделали эти представления «не совсем подходящими». Но я использую их в других местах (таблица просмотрела меня на 90 процентов, но последние 10 процентов оказались сложными для реализации, используя tableview). Я согласен, что не изобретать волю - это здорово. – cdub

+0

@chris> Хорошо, просто измените код так, как я написал выше, и будьте счастливы ... Я уверен, что он решит вашу проблему. – FormigaNinja

1

Изменение класса UIView называется DiscoverView.h к

- (id)initWithFrame:(CGRect)frame andObjects:(PFObject *)objects; 

изменения файла реализации DiscoverView.м:

@interface DiscoverView() 
@property (nonatomic, strong) id photoObject; 
@end 
@implementation DiscoverView 

- (id)initWithFrame:(CGRect)frame andObjects:(PFObject *)objects { 

    //You can call initWithFrame: method here as our base constructor 
    self = [super initWithFrame:frame]; 

    if (self) { 

     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(discoverTapPressed)]; 
     [self addGestureRecognizer:tap]; 
     _photoObject = objects.objectId; 
     self.backgroundColor = [UIColor whiteColor]; 
     self.layer.cornerRadius = 2.0; 
     self.layer.borderColor = [UIColor redColor].CGColor; 
     self.layer.borderWidth = 1.0f; 
    } 

    return self; 
} 

- (void) discoverTapPressed 
{ 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"The id is:" 
                message:_photoObject 
                delegate:nil 
              cancelButtonTitle:@"OK" 
              otherButtonTitles:nil]; 
    [alert show]; 
} 

Замените код в ваш старый код:

DiscoverView *parent = [[DiscoverView alloc] init]; 
    [parent buildDiscoverViewWithFrame:frame andObjects:replies]; 
    // UIView *parent = [[UIView alloc] initWithFrame:CGRectMake(5.0, _viewStart, 310.0, viewHeight)]; 
    parent.backgroundColor = [UIColor whiteColor]; 
    // parent.layer.cornerRadius = 2.0; 
    parent.layer.borderColor = [UIColor regularColor].CGColor; 
    parent.layer.borderWidth = 1.0f; 
    parent.tag = 1000 + _step; 

в

DiscoverView *parent = [[DiscoverView alloc] initWithFrame:frame andObjects:replies]; 
    parent.tag = 1000 + _step; 
Смежные вопросы