2015-04-30 2 views
0

У меня есть UILabel и UITextField и UIButton Я поставил их в раскадровку и ограничивается их к SuperViewМожете ли вы использовать как раскадровки, так и программный код?

Позже я узнаю, что мне нужно UIScrollView, чтобы убедиться, что содержимое отображается правильно

Мои Код выглядит как

@property (weak, nonatomic) IBOutlet UITextField *passwordTextField; 
@property (weak, nonatomic) IBOutlet UITextField *passwordConfirmTextField; 
@property (weak, nonatomic) IBOutlet UILabel *directionsLabel; 
@property (weak, nonatomic) IBOutlet UIButton *saveButton; 

@property UIScrollView *scrollView; 
@property UIView *contentView; 

@property UITapGestureRecognizer *tap; 
@property CGSize kbSize; 

@end 

@implementation UserEditPasswordViewController 

- (void)viewWillAppear:(BOOL)animated 
{ 
    [self registerForKeyboardNotifications]; 
} 

-(void)viewWillDisappear:(BOOL)animated 
{ 
    [self deregisterFromKeyboardNotifications]; 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    self.directionsLabel.text = @"Enter in and confirm a new password. \n Leave blank for no changes"; 
    [self createScrollView]; 
    [self createContentView]; 
    [self addSubViews]; 
    [self customizeSaveButton]; 

} 

#pragma mark - ScrollView 

- (void)createScrollView 
{ 
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; 
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height); 
    self.scrollView.delegate = self; 
} 

#pragma mark - Create ContentView 
- (void)createContentView 
{ 
    self.contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)]; 
} 

#pragma mark - Add Subiews 
- (void)addSubViews 
{ 
    [self.view addSubview:self.scrollView]; 
    [self.scrollView addSubview:self.contentView]; 
    [self.contentView addSubview:self.saveButton]; 
    [self.contentView addSubview:self.passwordTextField]; 
    [self.contentView addSubview:self.passwordConfirmTextField]; 
    [self.contentView addSubview:self.directionsLabel]; 
} 

#pragma mark - Customize Save Button 
- (void)customizeSaveButton 
{ 
    self.saveButton.layer.cornerRadius = 5; 
    self.saveButton.clipsToBounds = YES; 
} 

#pragma mark - Tap Gesture 
- (void)tapGestureRecognizerEndsEditing 
{ 
    // tap gesture to dismiss the keybaord when user taps anywhere on screen 

    self.tap = [[UITapGestureRecognizer alloc] 
       initWithTarget:self 
       action:@selector(dismissKeyboard)]; 

    [self.view addGestureRecognizer:self.tap]; 
} 



#pragma mark - Keyboard Notifications 
- (void)registerForKeyboardNotifications { 

    // registers notifications for when the keyboard is shown and when the keyboard is hidden 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(keyboardWasShown:) 
               name:UIKeyboardDidShowNotification 
               object:nil]; 

    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(keyboardWillBeHidden:) 
               name:UIKeyboardWillHideNotification 
               object:nil]; 
} 

- (void)deregisterFromKeyboardNotifications { 

    // deregisters the keyboard notifications 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                name:UIKeyboardDidHideNotification 
                object:nil]; 

    [[NSNotificationCenter defaultCenter] removeObserver:self 
                name:UIKeyboardWillHideNotification 
                object:nil]; 
} 

- (void)keyboardWasShown:(NSNotification *)notification { 
    [self tapGestureRecognizerEndsEditing]; 
    NSDictionary *info = [notification userInfo]; 

    self.kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; 

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, self.kbSize.height, 0.0); 
    self.scrollView.contentInset = contentInsets; 
    self.scrollView.scrollIndicatorInsets = contentInsets; 

    CGRect aRect = self.view.frame; 
    aRect.size.height -= self.kbSize.height; 
    if (!CGRectContainsPoint(aRect, self.saveButton.frame.origin)) { 
     CGPoint scrollPoint = CGPointMake(0, self.saveButton.frame.origin.y-self.kbSize.height); 
     [self.scrollView setContentOffset:scrollPoint animated:YES]; 
    } 
    self.scrollView.scrollEnabled = TRUE; 
} 

- (void)keyboardWillBeHidden:(NSNotification *)notification 
{ 
    [self.scrollView setContentOffset:CGPointZero animated:YES]; 
    self.scrollView.scrollEnabled = false; 
} 

- (void)dismissKeyboard 
{ 
    // function to dismiss the keyboard 
    [self.view endEditing:YES]; 

    [self.tap removeTarget:self action:@selector(dismissKeyboard)]; 
} 

Но прокрутка не работает. Ярлык, текстовое поле и кнопка отображаются просто отлично.

Что я делаю неправильно? Можете ли вы использовать гибрид раскадровки И программный код или он один или другой?

+0

Попробуйте установить размер содержимого прокрутки в программном виде –

+0

Поменяйте сначала две строки: 'self.scrollView = [[UIScrollView alloc] initWithFrame: CGRectMake (0, 0, self.view.frame.size.width, self.view.frame. size.height)]; 'а затем' self.scrollView.delegate = self; ' –

+0

@kevin у вас установлен scrollViewContent Размер –

ответ

0

Да, мы можем использовать как

сначала мы должны создать объект Scrollview, затем добавить свои взгляды на Scrollview, пожалуйста, проверьте код, приведенный ниже, я попытался это работает нормально.

#import "ViewController.h" 

@interface ViewController() 
@property (weak, nonatomic) IBOutlet UILabel *helloWorldLabel; 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; 
    scrollView.delegate = self; 
    scrollView.backgroundColor = [UIColor redColor]; 
    [self.view addSubview:scrollView]; 
    [scrollView addSubview:self.helloWorldLabel]; 

} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

@end 

, если вы хотите, чтобы прокрутить Scrollview, увеличить размер контента Scrollview, как показано ниже

scrollView.contentSize = CGSizeMake(600, 2000); 
+0

Уже выделено init: self.scrollView = [[UIScrollView alloc] initWithFrame: CGRectMake (0, 0, self.view.frame.size.width, self.view.frame.size.height)]; –

+0

Я уже добавил UIViews и привязал их к супервизу, это только 3 объекта в раскадровке. Scrollview и добавление подпрограмм выполнялось программно. –

+0

в порядке, просьба указать код. И добавьте цвет фона в scrollview и отметьте один раз. –

1

Пожалуйста, установите делегат Scrollview.

self.scrollView.delegate = self; 

Я надеюсь, что это сработает для вас.

+0

Я ввел делегата. Смотрите мой код выше –

+0

@KevinL. да, но не в том месте. Как вы думаете, 'self.scrollView', прежде чем вы его выделите? –

+0

Я положил делегат после выделения init. Он по-прежнему не работает так, как должен, поскольку клавиатура скрывает кнопку сохранения, на которой у меня есть уведомления о клавиатуре, чтобы переместить scrollview вверх. Кажется, что scrollview присутствует, просто не двигаясь вверх –

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