How to load .xib UIviews on ViewController in ios - ios

Hi i am very new for ios and in my app i am loading UIView using .xib files
when i click first buttons i want to load FirstView and remove otherviews
when i click second button i want to load SecondView and remove otherviews
when i click third button i want to load ThirdView and remove otherviews
mycode:-
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize leftView,rightView;
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)FirstAction:(id)sender {
FirstView * test1 = [[FirstView alloc]initWithFrame:CGRectMake(0, 0, rightView.frame.size.width, rightView.frame.size.height)];
test1.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[rightView addSubview:test1];
}
- (IBAction)SecondAction:(id)sender {
SecondView * test2 = [[SecondView alloc]initWithFrame:CGRectMake(0, 0, rightView.frame.size.width, rightView.frame.size.height)];
test2.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[rightView addSubview:test2];
}
- (IBAction)ThirdAction:(id)sender {
ThirdView * test3 = [[ThirdView alloc]initWithFrame:CGRectMake(0, 0, rightView.frame.size.width, rightView.frame.size.height)];
test3.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[rightView addSubview:test3];
}
#end

Try this piece of code: I have written code for view which will remove previous view before adding the new one.
#import "ViewController.h"
#interface ViewController ()
{
FirstView * test1;
SecondView * test2;
ThirdView * test3;
}
#end
#implementation ViewController
#synthesize leftView,rightView;
- (void)viewDidLoad {
[super viewDidLoad];
test1 = [[[NSBundle mainBundle] loadNibNamed:#"FirstView" owner:self options:nil] objectAtIndex:0];
test2 = [[[NSBundle mainBundle] loadNibNamed:#"SecondView" owner:self options:nil] objectAtIndex:0];
test3 = [[[NSBundle mainBundle] loadNibNamed:#"ThirdView" owner:self options:nil] objectAtIndex:0];
}
- (IBAction)FirstAction:(id)sender {
test1.frame = CGRectMake(0, 0, rightView.frame.size.width, rightView.frame.size.height);
test1.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[self removePreviousView:test1 FromSuperView:rightView];
[rightView addSubview:test1];
}
- (IBAction)SecondAction:(id)sender {
test2.frame = CGRectMake(0, 0, rightView.frame.size.width, rightView.frame.size.height);
test2.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[self removePreviousView:test2 FromSuperView:rightView];
[rightView addSubview:test2];
}
- (IBAction)ThirdAction:(id)sender {
test3.frame = CGRectMake(0, 0, rightView.frame.size.width, rightView.frame.size.height);
test3.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[self removePreviousView:test3 FromSuperView:rightView];
[rightView addSubview:test3];
}
- (void)removePreviousView:(UIView*)previousView FromSuperView:(UIView*)view{
for (UIView *subView in view.subviews) {
if (![subView isKindOfClass:[previousView class]]) {
[subView removeFromSuperview];
}
}
}
#end

1)
Make view global
FirstView * test1;
SecondView * test2;
ThirdView * test3;
Remove from superview whenever you want:
[test1 removeFromSuperView];
2) Add tag to view
test1.tag = 10;
Remove view using tag value:
[(UIView*)[rightView viewWithTag:10] removeFromSuperview];

Use this code. It contains a loadXib: call that loads the view from the nib with the given name and returns it.
#interface ViewController ()
{
FirstView * test1;
SecondView * test2;
ThirdView * test3;
}
#end
#implementation ViewController
#synthesize leftView,rightView;
- (void)viewDidLoad {
[super viewDidLoad];
}
-(UIView*)loadXib:(NSString *)name
{
UINib *nib = [UINib nibWithNibName:name bundle:nil];
if (nib != nil)
{
NSArray *items = [nib instantiateWithOwner:self options:nil];
if (items != nil && items.count == 1)
{
return (UIView*)items[0];
}
}
return nil;
}
- (IBAction)FirstAction:(id)sender {
// test1 = [[FirstView alloc]initWithFrame:CGRectMake(0, 0, rightView.frame.size.width, rightView.frame.size.height)];
test1 = (FirstView*)[self loadXib:#"FirstView"];
if (test1 != nil) {
test1.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[rightView.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
[rightView addSubview:test1];
}
}
- (IBAction)SecondAction:(id)sender {
// test2 = [[SecondView alloc]initWithFrame:CGRectMake(0, 0, rightView.frame.size.width, rightView.frame.size.height)];
test2 = (SecondView*)[self loadXib:#"SecondView"];
if (test2 != nil) {
test2.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[rightView.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
[rightView addSubview:test2];
}
}
- (IBAction)ThirdAction:(id)sender {
// test3 = [[ThirdView alloc]initWithFrame:CGRectMake(0, 0, rightView.frame.size.width, rightView.frame.size.height)];
test3 = (ThirdView*)[self loadXib:#"ThirdView"];
if (test3 != nil ) {
test3.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[rightView.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
[rightView addSubview:test3];
}
}
#end

Below is method for your need.
/* Without tag */
- (void)removeSubviewsExpectView:(id)viewClass {
for (UIView *subView in self.view.subviews) {
if (![subView isKindOfClass:[viewClass class]]) {
[subView removeFromSuperview];
}
}
}
/* With tag */
- (void)removeSubviewsExpectView:(int)viewTag {
for (UIView *subView in self.view.subviews) {
if (subView.tag != viewTag) {
[subView removeFromSuperview];
}
}
}
Hope this helps you out.

Firstly you create UiView IBOutlets in the NSBundle then you choose this method
- (IBAction)FirstAction:(id)sender {
NSArray *viewsToRemove = [rightView subviews];
for (UIView *v in viewsToRemove) {
[v removeFromSuperview];
}
UIView *firstViewUIView = [[[NSBundle mainBundle] loadNibNamed:#"Test1" owner:self options:nil] firstObject];
[rightView containerView addSubview:firstViewUIView];
}
- (IBAction)SecondAction:(id)sender {
NSArray *viewsToRemove = [rightView subviews];
for (UIView *v in viewsToRemove) {
[v removeFromSuperview];
}
UIView *secondView = [[[NSBundle mainBundle] loadNibNamed:#"Test2" owner:self options:nil] firstObject];
[rightView containerView addSubview:seconView];
}
- (IBAction)ThirdAction:(id)sender {
NSArray *viewsToRemove = [rightView subviews];
for (UIView *v in viewsToRemove) {
[v removeFromSuperview];
}
UIView *thirdView = [[[NSBundle mainBundle] loadNibNamed:#"Test3" owner:self options:nil] firstObject];
[rightView containerView addSubview:thirdView];
}

Related

Changing label text in custom UIView on the fly

I have a custom view called TimeTooltipView. Here is the code:
TimeTooltipView.h
#import <UIKit/UIKit.h>
#interface TimeTooltipView : UIView
#property (weak, nonatomic) IBOutlet UILabel *timeLabel;
-(void)configureView;
#end
TimeTooltipView.m
#import "TimeTooltipView.h"
#implementation TimeTooltipView
-(id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:#"TimeTooltipView" owner:self options:nil];
UIView *mainView = [subviewArray objectAtIndex:0];
[self addSubview:mainView];
[self configureView];
}
return self;
}
-(void)configureView {
self.backgroundColor = [UIColor greenColor];
}
#end
I add a TimeTooltipView in a view controller, like so:
TimeTooltipView *timeTooltipView = [[TimeTooltipView alloc]
initWithFrame: CGRectMake(100, 100, 50, 50)];
timeTooltipView.timeLabel.text = #"TEST";
[self.view addSubview:timeTooltipView];
timeTooltipView.timeLabel.text = #"TEST2";
I need to change timeLabel's text on the fly from the view controller. Using the code above, the view gets added and has a green background color. But the label text never changes to "TEST" or "TEST2".
How can I change the custom view's label text on the fly?
-(id)initWithFrame:(CGRect)frame {
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:#"TimeTooltipView" owner:self options:nil];
//Instead of making it subView just replace it.
self = [subviewArray objectAtIndex:0];
self.frame = frame;
[self configureView];
return self;
}
-(void)configureView {
self.backgroundColor = [UIColor greenColor];
}

Creating a receipt style UIView

I am attempting to create a view to show a list of items and prices using two UILabels in a UIView.
In my UIViewController I call my subview LineItemView and pass data, and return the UIView to the main view that will hold the subviews.
Though my view is returning empty. The strings are null.
ViewController.m
#import "LineItemView.h"
//...
#property (weak, nonatomic) IBOutlet UIView *viewCharges;
//...
- (void)viewDidLoad {
[super viewDidLoad];
[self loadData];
}
- (void) loadData {
//Here we will fill in the viewCharges view
LineItemView * view = [[LineItemView alloc]init];
view.linePrice = #"1.00";
view.lineItem = #"Something";
[self.viewCharges addSubview:view];
}
LineItemView.h
#interface LineItemView : UIView {
UILabel * lblLineItem, *lblLinePrice;
}
#property (nonatomic,strong) NSString* lineItem;
#property (nonatomic,strong) NSString* linePrice;
LineItemView.m
#define LABEL_MINIMUM_HEIGHT 32
#define VERTICAL_MARGIN 5
#define HORIZONTAL_MARGIN 10
#implementation LineItemView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self createUI];
[self updateData];
NSLog(#"\n\n\n Line Item: %# Price: %# \n\n\n", self.lineItem, self.linePrice);
}
return self;
}
-(void) createUI {
lblLineItem = [[UILabel alloc] initWithFrame:CGRectZero];
lblLineItem.backgroundColor = [UIColor greenColor];
[self addSubview:lblLineItem];
lblLinePrice = [[UILabel alloc] initWithFrame:CGRectZero];
lblLinePrice.backgroundColor = [UIColor yellowColor];
[self addSubview:lblLinePrice];
}
- (void) updateLayout {
lblLineItem.frame = CGRectMake(HORIZONTAL_MARGIN, VERTICAL_MARGIN, 300, 35);
lblLinePrice.frame = CGRectMake(lblLineItem.frame.origin.x + lblLineItem.frame.size.width + HORIZONTAL_MARGIN, VERTICAL_MARGIN, 80, 35);
}
- (void) updateData {
lblLineItem.text = self.lineItem;
lblLinePrice.text = [NSString stringWithFormat:#"%0.2f", [self.linePrice floatValue]];
}
- (void) layoutSubviews {
[super layoutSubviews];
[self updateLayout];
}
What am I doing wrong?
If I want to continue calling LineItemView, how do I ensure that it is added below the previous one and ensure the viewCharges size is readjusted to fit all the subviews?
Solution using setters:
#implementation LineItemView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self createUI];
}
return self;
}
-(void) createUI {
lblLineItem = [[UILabel alloc] initWithFrame:CGRectZero];
lblLineItem.backgroundColor = [UIColor greenColor];
[self addSubview:lblLineItem];
lblLinePrice = [[UILabel alloc] initWithFrame:CGRectZero];
lblLinePrice.backgroundColor = [UIColor yellowColor];
[self addSubview:lblLinePrice];
}
- (void) updateLayout {
lblLineItem.frame = CGRectMake(HORIZONTAL_MARGIN, VERTICAL_MARGIN, 300, 35);
lblLinePrice.frame = CGRectMake(lblLineItem.frame.origin.x + lblLineItem.frame.size.width + HORIZONTAL_MARGIN, VERTICAL_MARGIN, 80, 35);
}
- (void) layoutSubviews {
[super layoutSubviews];
[self updateLayout];
}
- (void)setLineItem:(NSSTring *)lineItem {
_lineItem = lineItem;
lblLineItem.text = self.lineItem;
}
- (void)setLinePrice:(NSNumber *)linePrice {
_linePrice = linePrice;
lblLinePrice.text = [NSString stringWithFormat:#"%0.2f", [self.linePrice floatValue]];
}

How to pass delegate to a UITextField inside an IB_DESIGNABLE?

I have created a custom view and added a UITextField to it.My question is: How can I add a delegate so that the you can set it as the default cmd+drag behaviour of XCode?
My current attempt is by doing something like this:
In my .h file:
#import <UIKit/UIKit.h>
IB_DESIGNABLE
#interface CustomTextField : UIView
#property (assign, nonatomic) IBInspectable id textFieldDelegate;
#end
and my .m file:
#import "CustomTextField.h"
#interface CustomTextField()
#property (strong, nonatomic) IBOutlet UITextField *textField;
#end
#implementation CustomTextField
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
[self loadNib];
}
return self;
}
- (void)loadNib{
UIView *view = [[[NSBundle bundleForClass:[self class]] loadNibNamed:#"CustomTextField" owner:self options:nil] firstObject];
[self addSubview:view];
view.frame = self.bounds;
}
- (void)setTextFieldDelegate:(id)textFieldDelegate{
self.textField.delegate = textFieldDelegate;
}
#end
But it doest show up in the left panel of XCode, Connections Inspector Tab.
Also here is my current code.
Update 1:
also if using the code below I get a an error:
- (id)initWithFrame:(CGRect)aRect
{
self = [super initWithFrame:aRect];
if (self)
{
[self loadNib];
}
return self;
}
- (id)initWithCoder:(NSCoder*)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self loadNib];
}
return self;
}
- (void)loadNib{
//
// UIView *view = [[[NSBundle bundleForClass:[self class]] loadNibNamed:#"CustomTextField" owner:self options:nil] firstObject];
// [self addSubview:view];
// view.frame = self.bounds;
UIView *view = [[[NSBundle bundleForClass:[self class]] loadNibNamed:#"CustomTextField" owner:self options:nil] firstObject];
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:view];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[view]|­" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[view]|­" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];
self.textLabel.text = #"1";
}
Any suggestions on what should I do?
Update 2
I ended up by replacing the initWithFrame, initWithCoder and loadNib functions with:
- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder
{
if (![self.subviews count])
{
NSBundle *mainBundle = [NSBundle mainBundle];
NSArray *loadedViews = [mainBundle loadNibNamed:#"CustomTextField" owner:nil options:nil];
CustomTextField *loadedView = [loadedViews firstObject];
loadedView.frame = self.frame;
loadedView.autoresizingMask = self.autoresizingMask;
loadedView.translatesAutoresizingMaskIntoConstraints =
self.translatesAutoresizingMaskIntoConstraints;
for (NSLayoutConstraint *constraint in self.constraints)
{
id firstItem = constraint.firstItem;
if (firstItem == self)
{
firstItem = loadedView;
}
id secondItem = constraint.secondItem;
if (secondItem == self)
{
secondItem = loadedView;
}
[loadedView addConstraint:
[NSLayoutConstraint constraintWithItem:firstItem
attribute:constraint.firstAttribute
relatedBy:constraint.relation
toItem:secondItem
attribute:constraint.secondAttribute
multiplier:constraint.multiplier
constant:constraint.constant]];
}
return loadedView;
}
return self;
}

Objective-c OOP is this the best way to reuse my code from father class?

Im new in OOP and I've read some tutorials and books. I have the concept more or less clear but I haven't seen many examples. I've made a simple webView app which only displays a website and got some tabs and push notifications. It's not the big deal. Almost all the code from father class can be reused, and no need to rewrite it, so I've made some inheritance and overriding solutions to childrens, but I'm would like to know if the way I did it is the correct approach to object oriented way, also with the design and even with the code documentation. I need to show this code in a future job interview and I would like to refine it and also learn about experts from here with with more experience than I have.
Any help would be highly appreciated and many thanks!
This is my father class:
//
// FirstViewController.h
#import <UIKit/UIKit.h>
#import "iAd/iAd.h"
#interface FirstViewController : UIViewController <UIWebViewDelegate,UIGestureRecognizerDelegate, ADBannerViewDelegate, UIScrollViewDelegate>
#property (strong, nonatomic) IBOutlet UITabBarItem *tabInicio;
+(void)viewController:(NSString*)link;
-(void)configureView:(UIViewController*)vista;
-(void)iAdDisplay:(UIViewController*)vista;
-(void)autoResizeWhenRotates:(UIViewController*)vista;
-(void)configureWebView:(UIViewController *)vista withUrlLink:(NSURL *)url;
-(void)showHideStatusBar:(UIViewController*)vista;
-(void)addGestures:(UIViewController*)vista;
-(void)configureToolBar:(UIViewController*)vista;
-(void)addIndicator:(UIViewController*)vista;
#end
And the implementation file:
//
// FirstViewController.m
// push
//
#import "FirstViewController.h"
#interface FirstViewController ()
#property UIActivityIndicatorView *indicator;
#property UIToolbar *cToolBar;
#property BOOL isHidden;
#end
#implementation FirstViewController
static UITabBarController *static_Tab = nil;
static UIWebView* static_iVar = nil;
- (void)viewDidLoad {
[super viewDidLoad];
[self configureView:self];
//configure autoresize when device rotate
NSURL *url = [NSURL URLWithString:#"http://hnoslopez.com"];
[self configureStatic_iVar:self withUrlLink:url];
//Set tab bar icons
[[[self.tabBarController.viewControllers objectAtIndex:1] tabBarItem]setImage:[UIImage imageNamed:#"nosotros.png"]];
[[[self.tabBarController.viewControllers objectAtIndex:2] tabBarItem]setImage:[UIImage imageNamed:#"catalogo.png"]];
[[[self.tabBarController.viewControllers objectAtIndex:3] tabBarItem]setImage:[UIImage imageNamed:#"blog.png"]];
self.tabBarController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.tabBarController.view.autoresizesSubviews = YES;
//Set first tab
_tabInicio = [[UITabBarItem alloc] initWithTitle:#"Inicio" image:[UIImage imageNamed:#"inicioIcon.png"] tag:0];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]];
[self.tabBarController setSelectedIndex:0];
self.tabBarItem = _tabInicio;
}
-(void)configureView:(UIViewController *)vista{
//configure toolbar
[self configureToolBar:vista];
//show hide status bar with a gesture recognizer and an animation
[self showHideStatusBar:vista];
//iAd display
[self iAdDisplay:vista];
//auto resizing when device rotates
[self autoResizeWhenRotates:vista];
//Add gestures
[self addGestures:vista];
//Add Indicator
[self addIndicator:vista];
}
-(void)configureToolBar:(UIViewController *)vista{
//Add a toolbar, back and reload button...
UIToolbar *cToolBar = [[UIToolbar alloc] init];
//auto resizing
cToolBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingNone;
cToolBar.autoresizesSubviews = YES;
cToolBar.frame = CGRectMake(0, 0, vista.view.frame.size.width, 44);
NSMutableArray *items = [[NSMutableArray alloc] init];
//Set toolbar properties..
[cToolBar setBarStyle:UIBarStyleBlack];
[cToolBar setTranslucent:YES ];
[cToolBar setTintColor:[UIColor greenColor]];
//Back Button..
NSString *backArrowString = #"\U000025C0\U0000FE0E Atrás"; //BLACK LEFT-POINTING TRIANGLE PLUS VARIATION SELECTOR
UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithTitle:backArrowString style:UIBarButtonItemStyleDone target:nil action:#selector(goBack)];
//Reload button..
UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:nil action:#selector(refreshControl)];
[right setTintColor:[UIColor greenColor]];
//Flexible space between buttons..
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[items addObject:back];
[items addObject:flexibleSpace];
[items addObject:right];
[cToolBar setItems:items animated:NO];
[vista.view addSubview:cToolBar];
}
-(void)showHideStatusBar:(UIViewController *)vista{
//Animation performed to hide/show bar when slide your finger..
if ([vista respondsToSelector:#selector(setNeedsStatusBarAppearanceUpdate)]) {
// iOS 7
[vista performSelector:#selector(setNeedsStatusBarAppearanceUpdate)];
} else {
// iOS 6
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
}
}
-(void)iAdDisplay:(UIViewController*)vista{
//Display iAd..
[vista setCanDisplayBannerAds:YES];
ADBannerView * adView = [[ADBannerView alloc] initWithFrame:CGRectZero];
adView.frame = CGRectOffset(adView.frame, 0, 44);
adView.delegate = self;
//resizing
adView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
adView.autoresizesSubviews = YES;
[vista.view addSubview:adView];
}
-(void)autoResizeWhenRotates:(UIViewController*)vista{
vista.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
vista.view.autoresizesSubviews = YES;
}
-(void)addGestures:(UIViewController*)vista{
//SWIPE DOWN
UISwipeGestureRecognizer *gest1 = [[UISwipeGestureRecognizer alloc] initWithTarget:vista action:#selector(hideTabBar:)];
gest1.delegate = self;
[gest1 setDirection:UISwipeGestureRecognizerDirectionDown];
[vista.view addGestureRecognizer:gest1];
//SWIPE UP
UISwipeGestureRecognizer *gest2 = [[UISwipeGestureRecognizer alloc] initWithTarget:vista action:#selector(showTabBar:)];
gest2.delegate = self;
[gest2 setDirection:UISwipeGestureRecognizerDirectionUp];
[vista.view addGestureRecognizer:gest2];
}
-(void)addIndicator:(UIViewController *)vista{
//loading indicator
// _indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
UIActivityIndicatorView* indicador = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[indicador setCenter:vista.view.center];
[indicador setHidesWhenStopped:YES];
//resizing
indicador.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
indicador.autoresizesSubviews = YES;
[vista.view addSubview:indicador];
[indicador startAnimating];
}
-(void)configureWebView:(UIViewController *)vista withUrlLink:(NSURL *)url{
//Children method to configure children webViews...
float width = [UIScreen mainScreen].bounds.size.width;
float height = [UIScreen mainScreen].bounds.size.height;
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, width,height)];
webView.delegate = self;
//ADD Delegate to disable lateral scroll
webView.scrollView.delegate = self;
//auto resizing
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
webView.autoresizesSubviews = YES;
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[vista.view addSubview:webView];
}
-(void)configureStatic_iVar:(UIViewController *)vista withUrlLink:(NSURL *)url{
//Configure father class webView...
float width = [UIScreen mainScreen].bounds.size.width;
float height = [UIScreen mainScreen].bounds.size.height;
static_iVar = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, width,height)];
static_iVar.delegate = self;
//ADD Delegate to disable lateral scroll
static_iVar.scrollView.delegate = self;
//auto resizing
static_iVar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
static_iVar.autoresizesSubviews = YES;
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[static_iVar loadRequest:requestObj];
[vista.view addSubview:static_iVar];
}
#pragma - mark selectors
-(void)goBack{
NSArray *subviews = [self.view subviews];
for (UIView *subview in subviews){
if([subview isKindOfClass:[UIWebView class]] && [subview respondsToSelector:#selector(goBack)])
{
[subview performSelector:#selector(goBack)];
}
}
}
-(void)refreshControl{
[super viewDidAppear:YES];
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(startAnimating)])
{
[subview performSelector:#selector(startAnimating)];
}
if([subview isKindOfClass:[UIWebView class]] && [subview respondsToSelector:#selector(reload)])
{
[subview performSelector:#selector(reload)];
}
}
}
- (void) hideTabBar:(UITabBarController *) tabbarcontroller
{
//Perform animation to hide tab bar
CGRect screenRect = [[UIScreen mainScreen] bounds];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
float fHeight = screenRect.size.height;
for(UIView *view in self.tabBarController.view.subviews)
{
if([view isKindOfClass:[UITabBar class]])
{
[view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
}
}
[UIView commitAnimations];
}
- (void) showTabBar:(UITabBarController *) tabbarcontroller
{
//Perform animation to show tab bar..
CGRect screenRect = [[UIScreen mainScreen] bounds];
float fHeight = screenRect.size.height - self.tabBarController.tabBar.frame.size.height;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
for(UIView *view in self.tabBarController.view.subviews)
{
if([view isKindOfClass:[UITabBar class]] )
{
[view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
}
}
[UIView commitAnimations];
}
+(void)viewController:(NSString*)link{
//Loads push notification links in first tab..
NSURL *url = [NSURL URLWithString:link];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[static_iVar loadRequest:requestObj];
}
#pragma mark - delegate methods
- (void)webViewDidStartLoad:(UIWebView *)webView
{
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(startAnimating)])
{
[subview performSelector:#selector(startAnimating)];
}
}
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
if([subviews count] == 0)
{
return;
}
else
{
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(stopAnimating)])
{
[subview performSelector:#selector(stopAnimating)];
}
}
}
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
if([subviews count] == 0)
{
return;
}
else
{
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(stopAnimating)])
{
[subview performSelector:#selector(stopAnimating)];
}
}
}
CGSize contentSize = webView.scrollView.contentSize;
CGSize viewSize = self.view.bounds.size;
float rw = viewSize.width / contentSize.width;
webView.scrollView.minimumZoomScale = rw;
webView.scrollView.maximumZoomScale = rw;
webView.scrollView.zoomScale = rw;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return TRUE;
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
return YES;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
[scrollView setContentOffset:CGPointMake(0, scrollView.contentOffset.y)];
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
And this is a children viewController:
//
// SecondViewController.h
//
#import <UIKit/UIKit.h>
#import "iAd/iAd.h"
#import "FirstViewController.h"
#interface secondViewController : FirstViewController <UIWebViewDelegate,UIGestureRecognizerDelegate,ADBannerViewDelegate, UIScrollViewDelegate>
#property (weak, nonatomic) IBOutlet UIWebView *secondView;
#property (strong, nonatomic) IBOutlet UITabBarItem *secondTab;
#end
Implementation file:
//
// SecondViewController.m
//
//
#import "secondViewController.h"
#import "iAd/iAd.h"
#interface secondViewController ()
#property UIActivityIndicatorView *indicador;
#end
#implementation secondViewController
- (void)viewDidLoad {
[super viewDidLoad];
[super configureView:self];
//configure webView
NSURL *url = [NSURL URLWithString:#"http://hnoslopez.com/nosotros/"];
[self configureWebView:self withUrlLink:url];
//Configure second tab
_secondTab = [[UITabBarItem alloc] initWithTitle:#"Nosotros" image:[UIImage imageNamed:#"nosotros.png"] tag:1];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]];
[self.tabBarController setSelectedIndex:1];
self.tabBarItem = _secondTab;
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
-(void)goBack{
//reloads webView
NSArray *subviews = [self.view subviews];
for (UIView *subview in subviews){
if([subview isKindOfClass:[UIWebView class]] && [subview respondsToSelector:#selector(goBack)])
{
[subview performSelector:#selector(goBack)];
}
}
}
-(void)refreshControl{
[super viewDidAppear:YES];
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
if([subviews count] == 0)
{
return;
}
else
{
for (UIView *subview in subviews)
{
//start animating indicator
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(startAnimating)])
{
[subview performSelector:#selector(startAnimating)];
}
//reloads webView
if([subview isKindOfClass:[UIWebView class]] && [subview respondsToSelector:#selector(reload)])
{
[subview performSelector:#selector(reload)];
}
}
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
if([subviews count] == 0)
{
return;
}
else
{
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(startAnimating)])
{
[subview performSelector:#selector(startAnimating)];
}
}
}
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
if([subviews count] == 0)
{
return;
}
else
{
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(stopAnimating)])
{
[subview performSelector:#selector(stopAnimating)];
}
}
}
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//iterate an array of subviews and finds indicator
NSArray *subviews = [self.view subviews];
if([subviews count] == 0)
{
return;
}
else
{
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIActivityIndicatorView class]] && [subview respondsToSelector:#selector(stopAnimating)])
{
[subview performSelector:#selector(stopAnimating)];
}
}
}
CGSize contentSize = webView.scrollView.contentSize;
CGSize viewSize = self.view.bounds.size;
float rw = viewSize.width / contentSize.width;
webView.scrollView.minimumZoomScale = rw;
webView.scrollView.maximumZoomScale = rw;
webView.scrollView.zoomScale = rw;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return TRUE;
}
- (void) hideTabBar:(UITabBarController *) tabbarcontroller
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
float fHeight = screenRect.size.height;
for(UIView *view in self.tabBarController.view.subviews)
{
if([view isKindOfClass:[UITabBar class]])
{
[view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
}
}
[UIView commitAnimations];
}
- (void) showTabBar:(UITabBarController *) tabbarcontroller
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
float fHeight = screenRect.size.height - self.tabBarController.tabBar.frame.size.height;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
for(UIView *view in self.tabBarController.view.subviews)
{
if([view isKindOfClass:[UITabBar class]] )
{
[view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
}
}
[UIView commitAnimations];
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
return YES;
}
#pragma mark resuelve problema de que la pagina hace scroll horizontal
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
[scrollView setContentOffset:CGPointMake(0, scrollView.contentOffset.y)];
}
#end

Displaying an alert view similar to UIAlertView

I am trying to create a custom "alert view", nothing too fancy I just want to display a view overtop of the current view just like a UIAlertView.
Now here is the problem...I made the view in a nib file and now I want to alloc/init the view whenever I need to present an alert.Can anyone help me?
This is my attempt to get the view initialized...as of right now this crashes my app when I alloc/init a new alert view.
The app is crashing by telling me the view is not key-value compliant for the outlets.. I definitely have the outlets hooked up properly, unless I have a "File's Owner" thing screwed up.
NSObject 0x14e49800> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key....
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self load];
}
return self;
}
- (void)load {
NSArray *views = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil];
[self addSubview:[views firstObject]];
}
- (void)awakeFromNib {
[super awakeFromNib];
}
- (id)initWithFrame:(CGRect)frame
{
self = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil][0];
if (self) {
[self addSubview:self.contentView];
self.frame = frame;
}
return self;
}
- (instancetype)initWithTitle:(NSString *)title
message:(NSString *)message
delegate:(id)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle
confirmButtonTitle:(NSString *)confirmButtonTitle {
self = [self initWithFrame:CGRectMake(0, 0, 320, 568)];
if (self) {
}
return self;
}
I made this method to present the view, just a simple addSubview...
- (void)showInView:(UIView *)view {
[view addSubview:self];
}
Try disabling autolayout and run the code.
Create a class same as below
#import "MyOverLay.h"
#interface MyOverLay (){
// control declarations
UIActivityIndicatorView *activitySpinner;
UILabel *loadingLabel;
}
#end
#implementation AcuOverLay
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)show:(NSString *)message{
// configurable bits
self.backgroundColor = [UIColor blackColor];
self.alpha = 0.75f;
self.autoresizingMask =UIViewAutoresizingFlexibleHeight;
float labelHeight = 22;
float labelWidth = self.frame.size.width - 20;
// derive the center x and y
float centerX = self.frame.size.width / 2;
float centerY = self.frame.size.height / 2;
// create the activity spinner, center it horizontall and put it 5 points above center x
activitySpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activitySpinner.frame = CGRectMake(centerX - (activitySpinner.frame.size.width / 2) , centerY - activitySpinner.frame.size.height - 20, activitySpinner.frame.size.width, activitySpinner.frame.size.height);
activitySpinner.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[self addSubview:activitySpinner];
[activitySpinner startAnimating];
// create and configure the "Loading Data" label
loadingLabel = [[UILabel alloc]initWithFrame:CGRectMake(centerX - (labelWidth / 2), centerY + 20 , labelWidth, labelHeight)];
loadingLabel.backgroundColor = [UIColor clearColor];
loadingLabel.textColor = [UIColor whiteColor];
loadingLabel.text = message;
loadingLabel.textAlignment = NSTextAlignmentCenter;
loadingLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[self addSubview:loadingLabel];
}
- (void)hide{
[UIView animateWithDuration:0.5 animations:^{
self.alpha = 0;
[self removeFromSuperview];
}];
}
#end
then create instance wherever you want
loadingOverlay = [[MyOverLay alloc]initWithFrame:[UIScreen mainScreen].bounds];
loadingOverlay.tag = 999;
[[[UIApplication sharedApplication] keyWindow] addSubview:loadingOverlay];
[loadingOverlay show:#"Saving ..."];

Resources