Tagged: code

Blocks save the day

I’m consistently amazed how useful blocks are in Objective-C. So much so that I’ll be attempting to document useful ways that blocks can make your life easier as an iOS developer. Here’s the first of (hopefully) many posts of its kind.

Take this code

- (void)viewDidAppear:(BOOL)animated {
{
    UIView *viewToAnimate = ...
    [self performSelector:@selector(animateIt:) withObject:viewToAnimate afterDelay:1.0f];
}

-(void)animateIt:(id)sender 
{
    // animate viewToAnimate
}

It seems like this could be better by having the animation code where you have your selector delay setup. Well guess what? Blocks to the rescue!

@implementation NSObject (PerformBlockAfterDelay)

- (void)performBlock:(void (^)(void))block 
          afterDelay:(NSTimeInterval)delay 
{
    block = [[block copy] autorelease];
    [self performSelector:@selector(fireBlockAfterDelay:) 
               withObject:block 
               afterDelay:delay];
}

- (void)fireBlockAfterDelay:(void (^)(void))block 
{
    block();
}

@end

This snippet is using category that you can #import into your class. Using this in practice you get this.

- (void)viewDidAppear:(BOOL)animated {
{
    UIView *viewToAnimate = ...
    [self performBlock:^void() {
        // animate viewToAnimate
    } afterDelay:1.0f];
}

Credit goes out to this StackOverflow thread for the tip.

More

Creating a login form with jQuery

View Demo

Creating a login (or any form for that matter) can be trickier than it looks. After all how difficult can two text boxes a button and some labels be? There are different ways to accomplish this task, some using more proper semantically correct markup techniques than others. This example will attempt to give a real world case of how easy it can be to target elements contained inside the form with minimal scripting using the jQuery framework.

We’ll first start out with some html markup, notice the lack of css class attributes or JavaScript event handlers present.

<fieldset>
	<legend>Log In</legend>
	<p id="loginResult">Invalid login.. try again.</p>
	<form id="login" method="post">
		<dl>
			<dt><label for="username">Username:</label></dt>
			<dd><input id="username" type="text" /></dd>
			<dt><label for="password">Password:</label></dt>
			<dd><input id="password" type="text" /></dd>
		</dl>
		<p><input type="submit" value="Login" /></p>
	</form>
	<small>u:username / p:password</small>
</fieldset>

The next step we take is to target each element down the list and assign it a css class. We do this by using jQuery’s element specific selectors :text and :submit.

	$(function(){
		$('form#login :text').addClass('inputTextbox');
		$('form#login :submit').addClass('inputSubmitBtn');
	});

Next, we’ll add the event handler for the submit button by using .click(). To make things easier on ourselves we could always shorten our code by chaining the click event at the end of our submit button selector which was already defined in the previous step.

$('form#login :submit').addClass('inputSubmitBtn').click(function() {
     // click event code
}

Throw in an animation for good measure to display a message for invalid attempts and you’re good to go. Here is the full JavaScript code we’re working with.

		$(function(){
			$('form#login :text').addClass('inputTextbox');
			$('form#login :submit').addClass('inputSubmitBtn').click(function(){
				if($('#username').val() != "username" || $('#password').val() != "password")
				{
					for(i=0;i<5;i++)
						$("#loginResult").animate({opacity: 'toggle'}, 500 );	
						
					$("#loginResult").fadeIn(500);					
					return false;
				};
			});
	    });
More

jQuery Framework First Impressions

Javascript frameworks come in a variety of flavors, they’ll typically encapsulate common practices that web developers frequently use in their sites. With the three dominant mainstream browsers (FF3, IE7, Safari and potentially even more) to worry about, each with a slightly different technique to program for, it can be a good practice to use a tested framework which works across the board and remove the overhead associated with testing common methods.

The framework which I’ve come to grow quite fond of lately is called jQuery. JQuery is best described as a type of web designers toy box that focuses on separating content from functionality. So what do I mean by this?

Here is an example setup for a jQuery project.

Sample jQuery Page Structure
$(document).ready(function(){
   $("#Button1").click(function(event){
	alert("Say Something");
 });
});

Whats nice about jQuery is that the footprint is relatively small at 54k or less, and if you prefer there is a file hosted from the Google API website which you can link to directly inside of your page. In fact you’ll find that many tasks require a minimal amount of code to achieve some impressive results.

// Resize lightbox on button click

$(document).ready(function(){
   $("#Button1").click(function(){
      $("#lightbox").animate({
          width: "1000px", 
          height: "400px", 
          fontSize: "3em"
      });
   });
});

Those familiar with object oriented programming will be glad to know that jQuery also supports chainability as in this example.

$("a").addClass("test").show().html("foo");

The jQuery framework is becoming increasingly popular among many high profile sites such as Netflix, NBC and Dell to name a few. Even the Microsoft development community is taking notice as their next update of Visual Studio will be providing jQuery code completion within the software itself.

For more information on jQuery you can visit their website: http://jquery.com/

More