Search This Blog

Sunday, August 23, 2015

How to careate a view programmatically in IOS?

UIWindow* window = [UIApplication sharedApplication].keyWindow;

UIView *polygonView = [[UIView alloc] initWithFrame: CGRectMake ( 0, 0, 200, 150)];
//add code to customize, 
polygonView.backgroundColor = [UIColor blackColor];

[window addSubview:polygonView];
[polygonView release];
 
This is a pattern you will use for not only this but subviews afterwards. Also, another note is with many of the templates, the viewController is already set up with it's own view. When you want to make a custom view, you create it like above but instead of the method above you set the viewControllers view to the newly created view like so:
 
viewController.view = polygonView;
 
======================================================================== 
 
UIView *newView = [[UIView alloc] initWithFrame:mainView.bounds];
[mainView addSubview:newView];
[newView release]; 

Size classes [How to programmatically implement 2 different layouts using size classes]

Scenario: I have a 6 buttons layout. In portrait they should be shown one above the other. In landscape they should be in 2 columns each with 3 buttons.

Use: You can examine the view's trait collection to determine its horizontal and vertical size class.

if ([self.view respondsToSelector:@selector(traitCollection)]){

    if (self.view.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
    ...
    }

}
 
Implement the traitCollectionDidChange: method to automatically be called when a trait changes due to autorotation.

For more information, see UITraitCollection Class Reference and UITraitEnvironment Protocol Reference.

References:
  1. http://stackoverflow.com/questions/25685829/programmatically-implementing-two-different-layouts-using-size-classes
 

Auto Layout [Programmatically]

Auto Layout is a system that lets you lay out your app’s user interface by creating a mathematical description of the relationships between the elements. You define these relationships in terms of constraints either on individual elements, or between sets of elements. Using Auto Layout, you can create a dynamic and versatile interface that responds appropriately to changes in screen size, device orientation, and localization.

How does it work?
Constraints: mathematically defines the relation between 2 views

NSObject > NSLayoutConstraint
+ constraintsWithVisualFormat:options:metrics:views:
+ constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:

Auto Layout is a new way to define dynamic GUIs. Before, we had autoresizing masks, that described how a subview will resize or move when its superview is resized. With Auto Layout you can do the same and also a lot more complicated GUIs quite easily.

Visual Format Language


 



Programmatically auto layout example:


// defined properties inside .h file

// local variables
@property (strong, nonatomic) IBOutlet UILabel *firstName;
@property (strong, nonatomic) IBOutlet UILabel *lastName;
@property (strong, nonatomic) IBOutlet UITextView *textView;
@property (strong, nonatomic) IBOutlet UIImageView *imageView;

// implementation of .m file

- (void)viewDidLoad
{
    [super viewDidLoad];
 
    [self addConstraints];
}

- (void) addConstraints {
    
    [self.view removeConstraints:self.view.constraints];
    
    
    UILabel *firstName = self.firstName;
    UILabel *lastName = self.lastName;
    UIImageView *imageView = self.imageView;
    UITextView *comment = self.textView;
    
    NSDictionary *views = NSDictionaryOfVariableBindings(firstName,lastName,imageView,comment);
    
    NSDictionary *metrics = @{@"width": @160.0, @"horizontalSpacing":@15.0, @"verticalSpacing":@10};
    
    NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:
                            @"H:|-[imageView(100)]-horizontalSpacing-[firstName(>=width)]-|"
                                                                   options:NSLayoutFormatAlignAllTop
                                                                   metrics:metrics
                                                                     views:views];
    
    constraints = [constraints arrayByAddingObjectsFromArray:
                   [NSLayoutConstraint constraintsWithVisualFormat:
                    @"H:[imageView]-horizontalSpacing-[lastName(>=width)]-|"
                                                           options:0
                                                           metrics:metrics
                                                             views:views]];

    constraints = [constraints arrayByAddingObjectsFromArray:
                   [NSLayoutConstraint constraintsWithVisualFormat:
                    @"H:[imageView]-horizontalSpacing-[comment(>=width)]-|"
                                                           options:NSLayoutFormatAlignAllBottom
                                                           metrics:metrics
                                                             views:views]];
// if you need to redefine the view, don't mention the Width Constraint again. 
// if you do, it will overlap. that's why, no Width Constraint is assigned in [imageView]

    constraints = [constraints arrayByAddingObjectsFromArray:
                   [NSLayoutConstraint constraintsWithVisualFormat:
                    @"V:|-50-[firstName]-verticalSpacing-[lastName]-verticalSpacing-[comment]"
                                                           options:0
                                                           metrics:metrics
                                                             views:views]];


    [self.view addConstraints:constraints];
    
}



Reference:
  1. Visual format language 
  2. Auto Layout Guide

Thursday, August 20, 2015

How to access app info.plist variables in code

Info.plist  [information property list file]:  is a structured text file that contains essential configuration information for a bundled executable

Attributes from the info.plist for your project are directly accessible by the following...

[[NSBundle mainBundle] objectForInfoDictionaryKey:key_name];


Example:  NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];


An information property list file is a structured text file that contains essential configuration information for a bundled executable. The file itself is typically encoded using the Unicode UTF-8 encoding and the contents are structured using XML. The root XML node is a dictionary, whose contents are a set of keys and values describing different aspects of the bundle. The system uses these keys and values to obtain information about your app and how it is configured. As a result, all bundled executables (plug-ins, frameworks, and apps) are expected to have an information property list file.

By convention, the name of an information property list file is Info.plist. This name of this file is case sensitive and must have an initial capital letter I. In iOS apps, this file resides in the top-level of the bundle directory. In OS X bundles, this file resides in the bundle’s Contents directory. Xcode typically creates this file for you automatically when you create a project of an appropriate type.

Difference between “Use auto layout” and “Use size class” in xcode 6.1?

They are two entirely different things.

Auto Layout:

"Use Auto Layout" determines whether a storyboard uses the Auto Layout features introduced in iOS 6 to automatically layout your interface using constraints.

“Auto Layout is a system that lets you lay out your app’s user interface by creating a mathematical description of the relationships between the elements. You define these relationships in terms of constraints either on individual elements, or between sets of elements.”

Size class:

Size classes require Auto Layout. If the checkbox Use Auto Layout isn’t selected when you select Use Size Classes, Xcode prompts you to enable Auto Layout.

"Use Size Classes" enables a new Xcode 6 feature called size classes that lets you use Auto Layout to build one interface for all devices and customize constraint constants, and certain views and constraints for different interface idioms while reusing the general layout. It saves the work and repetitiveness of having to build and maintain both MainiPhone and MainiPad storyboards.
 
Size Classes let you set different constraints for certain screen sizes. This let’s you go beyond basic stretching layouts.In Xcode 6 Apple introduced Size Classes.


Size classes. Size classes for iOS 8 enable designing a single universal storyboard with customized layouts for both iPhone and iPad. With size classes you can define common views and constraints once, and then add variations for each supported form factor. iOS Simulator and asset catalogs fully support size classes as well.



 Built a new project from scratch in Swift in Xcode 6 (Beta 1) and see File Inspector of Storyboard. There is Use Size Classes below Use Auto Layout. This is the screenshot of this.




Use size classes to enable a storyboard or xib file: to work with all available screen sizes. This enables the user interface of your app to work on any iOS device.
With size classes, a storyboard or xib file can be used for any available screen area. You build your interface as it will look in most sizes, then update only the parts that need to change when the available screen size changes.
A size class identifies a relative amount of display space for the height and for the width. Each dimension can be either compact, for example, the height of an iPhone in landscape orientation, or regular, for example, the height or width of an iPad. Because much of the layout of an app does not need to change for any available screen size, there is an additional value, any.
The available screen size for a view controller is based on 3 factors:
  • The screen size of the device.
  • The orientation of the device.
  • The portion of the screen available to the view controller. For example, when a split view controller displays both the master and detail controllers, neither controller has access to the full screen.
To create a view controller that uses size classes, begin by laying out your design abstractly—a height and width size class of any. To design for more specific available areas, choose appropriate size classes. As needed, add or remove views, change the font used to display text, and add, remove, or edit constraints. In this way, you can more easily deploy your app to different devices in various orientations.
You can change four aspects of presentation in a size class. For constraints, you can change the constant for a constraint and you can change whether the constraint is installed in the view hierarchy. For views, you can change whether a view is installed in the view hierarchy and you can change the font used to display text.
These four changes enable you to adapt your interface for a size class by:
  • Changing the size or position of views
  • Adding or removing views
  • Adding or removing constraints
  • Changing the font in labels, fields, text views, and buttons
As you design your app, preview how its layout appears on specific devices from within Xcode.

Create a text field, button programmatically

    UITextField *userNameField = [[UITextField alloc] initWithFrame:CGRectMake(20, 30, 300, 40)];
    userNameField.placeholder = @"userName";
    userNameField.accessibilityLabel = @"UserName Field";
    userNameField.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:userNameField];
   
   
    UITextField *passwordField = [[UITextField alloc] initWithFrame:CGRectMake(20, 90, 300, 40)];
    passwordField.placeholder = @"password";
    passwordField.secureTextEntry = YES;
    passwordField.accessibilityLabel = @"Password Field";
    passwordField.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:passwordField];
   
   
    UIButton * submitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    submitButton.frame = CGRectMake(20, 150, 150, 40);
    [submitButton setTitle:@"Submit" forState:UIControlStateNormal];
    submitButton.accessibilityLabel = @"Submit Button";
    [submitButton addTarget:self action:@selector(submitButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    submitButton.backgroundColor = [UIColor redColor];
    [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:submitButton];

Implementation example of button click:

-(void)submitButtonPressed:(id)Sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)loginButtonPressed:(id)sender{
    LoginViewController *loginViewController = [LoginViewController new];   // create a modal
    [self presentViewController:loginViewController animated:YES completion:nil];  // preent it as a model
}

Tell some of the KIF methods to test

waitForTappableViewWithAccessibilityLabel
waitForViewWithAccessibilityLabel

tapViewWithAccessibilityLabel

enterText:  intoViewWithAccessibilityLabel:

Examples:

    [tester waitForTappableViewWithAccessibilityLabel:@"Login Button"];
    [tester tapViewWithAccessibilityLabel:@"Login Button"];
    [tester waitForViewWithAccessibilityLabel:@"UserName Field"];
    [tester enterText:@"myUserName" intoViewWithAccessibilityLabel:@"UserName Field"];
    [tester enterText:@"myPassword" intoViewWithAccessibilityLabel:@"Password Field"];
    [tester tapViewWithAccessibilityLabel:@"Submit Button"];
   
    // Back to main view
    [tester waitForViewWithAccessibilityLabel:@"Login Button"];