本周开始学UIkit。纯代码写起来:》'-'《  。求请拍砖。

首先新建一个empty application

里面会有默认的appdelegate.h .m 文件

新建一个Objective-C class。  file-new-newfile-objective-c class 这个目录来添加

我的取名叫:MainViewController

后面就要开始手写了:UIKitAppDelegate.h

#import <UIKit/UIKit.h>
#import "MainViewController.h"

@interface UIKitAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (retain,nonatomic)  MainViewController *myViewController;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

@end

 

UIKitAppDelegate.m

代码大部分都是默认的。只需要改写

添加
@synthesize myViewController=_myViewController;

添加这个
-(void)dealloc
{
[_myViewController release];

}
改写
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

完整代码如下
#import "UIKitAppDelegate.h"

@implementation UIKitAppDelegate

@synthesize window = _window;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;

@synthesize myViewController=_myViewController;

- (void)dealloc
{
    [_window release];
    [_myViewController release];
    [__managedObjectContext release];
    [__managedObjectModel release];
    [__persistentStoreCoordinator release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    self.myViewController=[[MainViewController alloc]init];
    self.window.rootViewController=self.myViewController;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil)
    {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
        {
            /*
             Replace this implementation with code to handle the error appropriately.
             
             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}

#pragma mark - Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil)
    {
        return __managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}

/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil)
    {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"codeMyView" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"codeMyView.sqlite"];
    
    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
    {
        /*
         Replace this implementation with code to handle the error appropriately.
         
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    
    
    return __persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

@end

  

以上代码新建了一个window,并且将其rootviewcontroller 设为MainViewController类的实例myViewController

然后开始写MainViewController

MainViewController.h

#import <Foundation/Foundation.h>

@interface MainViewController : UIViewController
{
    UILabel *_mylabel;
    UIButton *_myButton;
    UIButton *_myButton2;
    UIButton *_myButton3;
    UIImageView *_myImageView;
    CGRect frame;
}   

@property (nonatomic,retain) UILabel *myLabel;
@property (nonatomic,retain) UIButton *myButton;
@property  (nonatomic,retain)   UIButton *myButton2;
@property   (nonatomic,retain)  UIButton *myButton3;
@property   (nonatomic,retain)  UIImageView *myImageView;


-(IBAction)myButtonPressed:(id)sender;

-(IBAction)myButton2Pressed:(id)sender;

-(IBAction)myButton3Pressed:(id)sender;
@end

  

MainViewController.m

@implementation MainViewController



@synthesize myLabel=_mylabel;
@synthesize myButton=_myButton;
@synthesize myButton2=_myButton2;
@synthesize myButton3=_myButton3;
@synthesize myImageView=_myImageView;


-(void)loadView
{
    UIView *view=[[UIView alloc]initWithFrame:[[UIScreen mainScreen]applicationFrame]];
    view.backgroundColor=[UIColor redColor];
    self.view=view;
    [view release];
    
    CGRect myLabelFrame=CGRectMake(100, 180, 120, 120);
    self.myLabel=[[UILabel alloc]initWithFrame:myLabelFrame];
    self.myLabel.text=@"This is a square";

    [self.myLabel setTextColor:[UIColor blackColor ]];
    [self.view addSubview:self.myLabel];
    [self.myLabel release];
    
    CGRect buttonFrame=CGRectMake(40, 40, 80, 20);
    [self.myButton =[UIButton alloc ]initWithFrame:buttonFrame];
    [self.myButton setTitle:@"Button1" forState:UIControlStateNormal];
    
    [self.myButton setBackgroundColor:[UIColor blackColor]];
    [self.myButton addTarget:self action:@selector(myButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.myButton];
    [self.myButton release];
    
    frame=CGRectMake(0, 400, 60, 60);
    self.myImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"1.png"]];
    [self.myImageView setFrame:frame]; 
    
    CGRect button2Frame=CGRectMake(40, 65, 80, 20);
    [self.myButton2=[UIButton alloc]initWithFrame:button2Frame];
    [self.myButton2 setTitle:@"Button2" forState:UIControlStateNormal];
    [self.myButton2 setBackgroundColor:[UIColor blackColor]];
    [self.myButton2 addTarget:self action:@selector(myButton2Pressed:) forControlEvents:UIControlEventTouchUpInside];
    
    CGRect button3Frame=CGRectMake(40, 90, 80, 20);
    [self.myButton3=[UIButton alloc]initWithFrame:button3Frame];
    [self.myButton3 setTitle:@"Button3" forState:UIControlStateNormal];
    [self.myButton3 setBackgroundColor:[UIColor blackColor]];
    [self.myButton3 addTarget:self action:@selector(myButton3Pressed:) forControlEvents:UIControlEventTouchUpInside];
    
}

-(IBAction)myButtonPressed:(id)sender
{
      
    [self.view addSubview:self.myImageView];
    
    [self.myImageView release];
    
    [self.view addSubview:self.myButton2];
    
    
    [self.myButton2 release];
    
    
}

-(IBAction)myButton2Pressed:(id)sender
{   
    [self.view addSubview:self.myButton3];    
    [self.myButton3 release];   
    [self.myImageView  startAnimating];
    [self.myImageView setAnimationDuration:1];
    frame.origin.x+=100;
    [self.myImageView setFrame:frame];
    [self.myImageView stopAnimating];
    
}

-(IBAction)myButton3Pressed:(id)sender
{
    
    [self.myImageView removeFromSuperview];
}


@end

  

bingo,完成了。

启动下,就会发现这个

 

我会告诉你吗?(这个代码中有坑

求填坑....

posted on 2012-11-23 12:56  xxppxiaowei  阅读(1806)  评论(2编辑  收藏  举报