posted by 프띠버리 2013. 10. 16. 15:18

DB를 이용한 간단 메모장 앱 완성본 파일


1. 테이블 및 셀 USER INTERFACE로 바꿈

2. 화면전환 효과 적용(메모장을 넘기고 펼치는듯한 느낌)

3.기존의 버튼들 아이콘화



MemoPad.zip



'Programing > IOS' 카테고리의 다른 글

DB를 이용한 간단 메모장 앱  (0) 2013.10.14
간단한 흔들기 제스쳐  (0) 2013.10.07
SQL 을 이용한 DB프로그램 테이블에 뿌리기  (0) 2013.10.07
세그먼트 연습  (0) 2013.10.04
구구단 퀴즈 프로그램 앱  (0) 2013.10.04
posted by 프띠버리 2013. 10. 14. 16:12


MemoData.h

#import <Foundation/Foundation.h>


@interface MemoData : NSObject

{

    NSInteger mIndex;

    NSString *mTitle;

    NSString *mContent;

    NSString *mDate;

}


@property(nonatomic, assign) NSInteger mIndex;

@property(nonatomic, retain) NSString *mTitle;

@property(nonatomic, retain) NSString *mContent;

@property(nonatomic, retain) NSString *mDate;


- (id)initWithData:(NSInteger)pIndex Title:(NSString *)pTitle Content:(NSString *)pContent Date:(NSString *)pDate;


@end




MemoData.m

#import "MemoData.h"


@implementation MemoData

@synthesize mIndex;

@synthesize mTitle;

@synthesize mContent;

@synthesize mDate;


- (id)initWithData:(NSInteger)pIndex Title:(NSString *)pTitle Content:(NSString *)pContent Date:(NSString *)pDate

{

    self.mIndex = pIndex;

    self.mTitle = pTitle;

    self.mContent = pContent;

    self.mDate = pDate;

    

    return self;

}


@end




MemoPadAppDelegate.h

#import <UIKit/UIKit.h>

#import <sqlite3.h>


@interface MemoPadAppDelegate : UIResponder <UIApplicationDelegate>

{

    UIWindow *window;

    UINavigationController *navigationController;

    NSString *DBName;

    NSString *DBPath;

    NSMutableArray *DBData;

    BOOL isFirstTimeAccess;

}


@property (retain, nonatomic) IBOutlet UIWindow *window;

@property (retain, nonatomic) IBOutlet UINavigationController *navigationController;

@property (retain, nonatomic) NSString *DBName;

@property (retain, nonatomic) NSString *DBPath;

@property (retain, nonatomic) NSMutableArray *DBData;

@property (assign) BOOL isFirstTimeAccess;


@property (nonatomic, assign) NSInteger currentMemoSQLIndex;

@property (nonatomic, assign) NSInteger currentMemoRowIndex;


- (void)checkAndreateDatabase;

- (void)readMemoFromDatabase;

- (void)writeMemoToDatabaseWithTitle:(NSString *)inputTitle Content:(NSString *)inputContent;

- (void)updateMemoToDatabaseWithTitle:(NSString *)inputTitle Content:(NSString *)inputContent;


- (void)deleteMemoFromDatabase;


@end




MemoPadAppDelegate.m

#import "MemoPadAppDelegate.h"

#import "RootViewController.h"

#import "MemoData.h"



@implementation MemoPadAppDelegate


@synthesize window;

@synthesize navigationController;

@synthesize DBData;

@synthesize DBName;

@synthesize DBPath;

@synthesize isFirstTimeAccess;


@synthesize currentMemoRowIndex;

@synthesize currentMemoSQLIndex;


- (void)dealloc

{

    [window release];

    [super dealloc];

}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    // 최초 액세스인가?

    self.isFirstTimeAccess = TRUE;

    

    // 앱의 파일 시스템 경로를 구한다.

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDir = [documentPaths objectAtIndex:0];

    

    // 데이터베이스 이름과 경로를 저장한다.

    self.DBName = @"MemoPad.db";

    self.DBPath = [documentsDir stringByAppendingPathComponent:self.DBName];

    

    [self checkAndreateDatabase];

    

    [window addSubview:[navigationController view]];

    [window makeKeyAndVisible];

    return YES;

}


- (void)checkAndreateDatabase

{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    

    if([fileManager fileExistsAtPath:self.DBPath])

    {

        return;

    }

    else

    {

        NSString *databasePathFromApp = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:self.DBName];

        [fileManager copyItemAtPath:databasePathFromApp toPath:self.DBPath error:nil];

    }

}


- (void)readMemoFromDatabase

{

    sqlite3 *database;

    

    // 데이터를 담을 오브젝트인 DBData 초기화 한다.

    // 데이터베이스에 처음 엑세스 하는 것이라면 alloc으로 메모리 할당

    if(self.isFirstTimeAccess == TRUE)

    {

        self.DBData = [[NSMutableArray alloc] init];

        self.isFirstTimeAccess = FALSE;

    }

    else // 처음 엑세스하는 것이 아니면 removeAllObject DBData 초기화 한다.

    {

        [self.DBData removeAllObjects];

    }

    

    // 데이터베이스 파일을 open 한다.

    if(sqlite3_open([self.DBPath UTF8String], &database) == SQLITE_OK)

    {

        const char *sqlStatement = "SELECT * FROM tblMemoPad ORDER BY MP_Index DESC";

        sqlite3_stmt *compiledStatement;

        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)

        {

            while(sqlite3_step(compiledStatement) == SQLITE_ROW)

            {

                NSInteger aIndex = sqlite3_column_int(compiledStatement, 0);

                NSString *aTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];

                NSString *aContent = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];

                NSString *aDate = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

                

                NSLog(@"%d  / %@  / %@  /  %@",aIndex, aTitle, aContent, aDate);

                

                MemoData *md = [[MemoData alloc] initWithData:aIndex Title:aTitle Content:aContent Date:aDate];

                [self.DBData addObject:md];

            }

        }

        else

        {

            printf("could not prepare statement : %s\n", sqlite3_errmsg(database));

        }

        sqlite3_finalize(compiledStatement);

    }

    sqlite3_close(database);

}


- (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

{

    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

}


- (void)writeMemoToDatabaseWithTitle:(NSString *)inputTitle Content:(NSString *)inputContent

{

    sqlite3 *database;

    

    if(sqlite3_open([self.DBPath UTF8String], &database) == SQLITE_OK)

    {

        const char *sqlStatement = "INSERT INTO tblMemoPad(MP_Title, MP_Content, MP_Date) VALUES(?,?,?)";

        sqlite3_stmt *compiledStatement;

        

        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)

        {

            NSDate *date = [NSDate date];

            NSCalendar *calendar = [NSCalendar currentCalendar];

            

            NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

            NSDateComponents *comp = [calendar components:unitFlags fromDate:date];

            

            NSString *yearOfCommonEra = [NSString stringWithFormat:@"%02d", [comp year]];

            NSString *monthOfYear = [NSString stringWithFormat:@"%02d", [comp month]];

            NSString *dayOfMonth = [NSString stringWithFormat:@"%02d", [comp day]];

            NSString *hourOfDay = [NSString stringWithFormat:@"%02d", [comp hour]];

            NSString *minuteOfHour = [NSString stringWithFormat:@"%02d", [comp minute]];

            NSString *secondOfMinute = [NSString stringWithFormat:@"%02d", [comp second]];

            

            NSString *dateStringConcat = [NSString stringWithFormat:@"%@-%@-%@", yearOfCommonEra, monthOfYear, dayOfMonth];

            NSString *timeStringConcat = [NSString stringWithFormat:@"%@:%@:%@", hourOfDay, minuteOfHour, secondOfMinute];

            

            NSString *dateTimeString = [NSString stringWithFormat:@"%@ %@", dateStringConcat, timeStringConcat];

            

            sqlite3_bind_text(compiledStatement, 1, [inputTitle UTF8String], -1, SQLITE_TRANSIENT);

            sqlite3_bind_text(compiledStatement, 2, [inputContent UTF8String], -1, SQLITE_TRANSIENT);

            sqlite3_bind_text(compiledStatement, 3, [dateTimeString UTF8String], -1, SQLITE_TRANSIENT);

            

            if(SQLITE_DONE != sqlite3_step(compiledStatement))

            {

                NSAssert1(0, @"Error while inserting into tblLocationHistory. '%s'", sqlite3_errmsg(database));

            }

            sqlite3_reset(compiledStatement);

            sqlite3_close(database);

        }

        else

        {

            printf("could not prepare statemont : %s\n", sqlite3_errmsg(database));

        }

    }

    else

    {

        sqlite3_close(database);

        

        NSAssert1(0, @"Error opening database in tblLocationHistory. '%s'", sqlite3_errmsg(database));

    }

}


- (void)updateMemoToDatabaseWithTitle:(NSString *)inputTitle Content:(NSString *)inputContent

{

    sqlite3 *database;

    

    if(sqlite3_open([self.DBPath UTF8String], &database) == SQLITE_OK)

    {

        NSString *sqlStatementNS = [[NSString alloc] initWithString:[NSString stringWithFormat:@"UPDATE tblMemoPad SET MP_Title=?, MP_Content=?, MP_Date=? WHERE MP_Index = '%d'", self.currentMemoSQLIndex]];

        

        NSLog(@"SQL = %@", sqlStatementNS);

        

        const char *sqlStatement = [sqlStatementNS UTF8String];

        

        sqlite3_stmt *compiledStatement;

        

        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)

        {

            NSDate *date = [NSDate date];

            NSCalendar *calendar = [NSCalendar currentCalendar];

            

            NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

            NSDateComponents *comp = [calendar components:unitFlags fromDate:date];

            

            NSString *yearOfCommonEra = [NSString stringWithFormat:@"%02d", [comp year]];

            NSString *monthOfYear = [NSString stringWithFormat:@"%02d", [comp month]];

            NSString *dayOfMonth = [NSString stringWithFormat:@"%02d", [comp day]];

            NSString *hourOfDay = [NSString stringWithFormat:@"%02d", [comp hour]];

            NSString *minuteOfHour = [NSString stringWithFormat:@"%02d", [comp minute]];

            NSString *secondOfMinute = [NSString stringWithFormat:@"%02d", [comp second]];

            

            NSString *dateStringConcat = [NSString stringWithFormat:@"%@-%@-%@", yearOfCommonEra, monthOfYear, dayOfMonth];

            NSString *timeStringConcat = [NSString stringWithFormat:@"%@:%@:%@", hourOfDay, minuteOfHour, secondOfMinute];

            

            NSString *dateTimeString = [NSString stringWithFormat:@"%@ %@", dateStringConcat, timeStringConcat];

            

            sqlite3_bind_text(compiledStatement, 1, [inputTitle UTF8String], -1, SQLITE_TRANSIENT);

            sqlite3_bind_text(compiledStatement, 2, [inputContent UTF8String], -1, SQLITE_TRANSIENT);

            sqlite3_bind_text(compiledStatement, 3, [dateTimeString UTF8String], -1, SQLITE_TRANSIENT);

            

            if(SQLITE_DONE != sqlite3_step(compiledStatement))

            {

                NSAssert1(0, @"Error while inserting into tblLocationHistory. '%s'", sqlite3_errmsg(database));

            }

            sqlite3_reset(compiledStatement);

            sqlite3_close(database);

        }

        else

        {

            printf("could not prepare statemont : %s\n", sqlite3_errmsg(database));

        }

    }

    else

    {

        sqlite3_close(database);

        

        NSAssert1(0, @"Error opening database in tblLocationHistory. '%s'", sqlite3_errmsg(database));

    }

    

}


- (void)deleteMemoFromDatabase

{

    sqlite3 *database;

    

    if(sqlite3_open([self.DBPath UTF8String], &database) == SQLITE_OK)

    {

        NSString *sqlStatementNS = [[NSString alloc] initWithString:[NSString stringWithFormat:@"DELETE FROM tblMemoPad WHERE MP_Index = '%d'", self.currentMemoSQLIndex]];

        const char *sqlStatement = [sqlStatementNS UTF8String];

        sqlite3_stmt *compiledStatement;

        

        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)

        {

            if(SQLITE_DONE != sqlite3_step(compiledStatement))

            {

                NSAssert1(0, @"Error while inserting into tblLocationHistory. '%s'", sqlite3_errmsg(database));

            }

            sqlite3_reset(compiledStatement);

        }

        sqlite3_finalize(compiledStatement);

    }

    sqlite3_close(database);

}


@end




RootViewController.h

#import <UIKit/UIKit.h>


@interface RootViewController : UITableViewController

{

    IBOutlet UIBarButtonItem *btnWrite;

}


- (IBAction)btnWriteTouched:(id)sender;


@end




RootViewController.m

#import "RootViewController.h"

#import "MemoPadAppDelegate.h"

#import "MemoData.h"

#import "ContentViewController.h"

#import "MemoWriteViewController.h"


@interface RootViewController ()


@end


@implementation RootViewController


- (id)initWithStyle:(UITableViewStyle)style

{

    self = [super initWithStyle:style];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    MemoPadAppDelegate *appDelegate = (MemoPadAppDelegate *)[[UIApplication sharedApplication] delegate];

    [appDelegate readMemoFromDatabase];

    

    self.title = @"MemoPad";

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


- (void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    MemoPadAppDelegate *appDelegate = (MemoPadAppDelegate *) [[UIApplication sharedApplication] delegate];

    [appDelegate readMemoFromDatabase];

    

    NSLog(@"reloadData");

    [self.tableView reloadData];

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    // Return the number of sections.

    return 1;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    MemoPadAppDelegate *appDelegate = (MemoPadAppDelegate *)[[UIApplication sharedApplication] delegate];

    

    int rowCount = [[appDelegate DBData] count];

    

    return rowCount;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    }

    

    MemoPadAppDelegate *appDelegate = (MemoPadAppDelegate *)[[UIApplication sharedApplication] delegate];

    MemoData *mData = [[appDelegate DBData] objectAtIndex:indexPath.row];

    

    cell.textLabel.text = mData.mTitle;

    

    return cell;

}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    ContentViewController *contentViewController = [[ContentViewController alloc] initWithNibName:@"ContentViewController" bundle:nil];

    

    MemoPadAppDelegate *appDelegate = (MemoPadAppDelegate *) [[UIApplication sharedApplication] delegate];

    

    [appDelegate setCurrentMemoRowIndex:indexPath.row];

    

    MemoData *tempData = [[appDelegate DBData] objectAtIndex:indexPath.row];

    [appDelegate setCurrentMemoSQLIndex:[tempData mIndex]];

    

    [self.navigationController pushViewController:contentViewController animated:YES];

}


- (IBAction)btnWriteTouched:(id)sender

{

    MemoWriteViewController *memoWriteViewController = [[MemoWriteViewController alloc] initWithNibName:@"MemoWriteViewController" bundle:nil];

    

    [self.navigationController presentViewController:memoWriteViewController animated:YES completion:nil];

    

}

@end




ContentViewController.h

#import <UIKit/UIKit.h>

#import "MemoData.h"


@interface ContentViewController : UIViewController<UIAlertViewDelegate>

{

    IBOutlet UILabel *labelDate;

    IBOutlet UILabel *labelTitle;

    IBOutlet UITextView *tvContent;

    IBOutlet UIBarButtonItem *btnDelete;

    IBOutlet UIBarButtonItem *btnEdit;

    IBOutlet UISlider *sliderFontSize;

    

    MemoData *mData;

}


- (IBAction)deleteMemo:(id)sender;

- (IBAction)editMemo:(id)sender;

- (IBAction)changeFontSize:(id)sender;


@property (retain, nonatomic) IBOutlet UILabel *labelDate;

@property (retain, nonatomic) IBOutlet UILabel *labelTitle;

@property (retain, nonatomic) IBOutlet UITextView *tvContent;

@property (retain, nonatomic) IBOutlet UIBarButtonItem *btnDelete;

@property (retain, nonatomic) IBOutlet UIBarButtonItem *btnEdit;

@property (retain, nonatomic) IBOutlet UISlider *sliderFontSize;

@property (retain, nonatomic) MemoData *mData;


@end




ContentViewController.m

#import "ContentViewController.h"

#import "MemoPadAppDelegate.h"

#import "MemoEditViewController.h"


@interface ContentViewController ()


@end


@implementation ContentViewController


@synthesize labelDate;

@synthesize labelTitle;

@synthesize tvContent;

@synthesize mData;

@synthesize btnDelete;

@synthesize btnEdit;

@synthesize sliderFontSize;


- (IBAction)changeFontSize:(id)sender

{

    int fontSizeValue = self.sliderFontSize.value;

    

    self.tvContent.font = [UIFont fontWithName:@"Helvetica" size:fontSizeValue];

}


- (IBAction)deleteMemo:(id)sender

{

    UIAlertView *alertView;


    alertView = [[UIAlertView alloc] initWithTitle:@"MemoPad" message:nil delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];

    [alertView setMessage:@"Do you want to delete the memo?"];

    [alertView show];

    [alertView release];

//    MemoEditViewController *memoEditViewController = [[MemoEditViewController alloc] initWithNibName:@"MemoEditViewController" bundle:nil];

//    [self.navigationController presentViewController:memoEditViewController animated:YES completion:nil];

//    [memoEditViewController release];

}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    if(buttonIndex == 1)

    {

        MemoPadAppDelegate *appDelegate = (MemoPadAppDelegate *) [[UIApplication sharedApplication] delegate];

        [appDelegate deleteMemoFromDatabase];

        [self.navigationController popViewControllerAnimated:YES];

    }

}


- (IBAction)editMemo:(id)sender

{

    MemoEditViewController *memoEditViewController = [[MemoEditViewController alloc] initWithNibName:@"MemoEditViewController" bundle:nil];

    

    [self.navigationController presentViewController:memoEditViewController animated:YES completion:nil];

    [memoEditViewController release];

}


- (void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

    MemoPadAppDelegate *appDelegate = (MemoPadAppDelegate *) [[UIApplication sharedApplication] delegate];

    self.mData = [[appDelegate DBData] objectAtIndex:[appDelegate currentMemoRowIndex]];

    

    self.labelDate.text = [self.mData mDate];

    self.labelTitle.text = [self.mData mTitle];

    self.tvContent.text = [self.mData mContent];

    self.tvContent.font = [UIFont fontWithName:@"Helvetica" size:12.0];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




MemoWriteViewController.h

#import <UIKit/UIKit.h>


@interface MemoWriteViewController : UIViewController<UITextViewDelegate>

{

    IBOutlet UITextField *tfTitle;

    IBOutlet UITextView *tvContent;

    IBOutlet UINavigationBar *navigationBar;

    IBOutlet UIBarButtonItem *btnSave;

    IBOutlet UIBarButtonItem *btnCancel;

}


@property (retain, nonatomic) IBOutlet UITextField *tfTitle;

@property (retain, nonatomic) IBOutlet UITextView *tvContent;

@property (retain, nonatomic) IBOutlet UINavigationBar *navigationBar;

@property (retain, nonatomic) IBOutlet UIBarButtonItem *btnSave;

@property (retain, nonatomic) IBOutlet UIBarButtonItem *btnCancel;


- (IBAction)saveMemo:(id)sender;

- (IBAction)cancelMemo:(id)sender;



@end




MemoWriteViewController.m

#import "MemoWriteViewController.h"

#import "MemoPadAppDelegate.h"


@interface MemoWriteViewController ()


@end


@implementation MemoWriteViewController


@synthesize tfTitle;

@synthesize tvContent;

@synthesize navigationBar;

@synthesize btnCancel;

@synthesize btnSave;


- (IBAction)saveMemo:(id)sender

{

    MemoPadAppDelegate *appDelegate = (MemoPadAppDelegate *)[[UIApplication sharedApplication] delegate];

    [appDelegate writeMemoToDatabaseWithTitle:[self.tfTitle text] Content:[self.tvContent text]];

    [self dismissViewControllerAnimated:YES completion:nil];

}


- (IBAction)cancelMemo:(id)sender

{

    [self dismissViewControllerAnimated:YES completion:nil];

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




MemoEditViewController.h

#import <UIKit/UIKit.h>

#import "MemoData.h"


@interface MemoEditViewController : UIViewController

{

    IBOutlet UITextField *tfTitle;

    IBOutlet UITextView *tvContent;

    IBOutlet UIBarButtonItem *btnSave;

    IBOutlet UIBarButtonItem *btnCancel;

    

    MemoData *mData;

}


@property(retain, nonatomic) IBOutlet UITextField *tfTitle;

@property(retain, nonatomic) IBOutlet UITextView *tvContent;

@property(retain, nonatomic) MemoData *mData;


- (IBAction)saveMemo:(id)sender;

- (IBAction)cancelMemo:(id)sender;


@end




MemoEditViewController.m

#import "MemoEditViewController.h"

#import "MemoPadAppDelegate.h"


@interface MemoEditViewController ()


@end


@implementation MemoEditViewController


@synthesize tfTitle;

@synthesize tvContent;

@synthesize mData;


- (IBAction)saveMemo:(id)sender

{

    MemoPadAppDelegate *appDelegate = (MemoPadAppDelegate *) [[UIApplication sharedApplication] delegate];

    

    [appDelegate updateMemoToDatabaseWithTitle:[self.tfTitle text] Content:[self.tvContent text]];

    [self dismissViewControllerAnimated:YES completion:nil];

}


- (IBAction)cancelMemo:(id)sender

{

    [self dismissViewControllerAnimated:YES completion:nil];

    

}


- (void)viewDidAppear:(BOOL)animated

{

    [self.tfTitle becomeFirstResponder];

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    

    MemoPadAppDelegate *appDelegate = (MemoPadAppDelegate *) [[UIApplication sharedApplication] delegate];

    self.mData = [[appDelegate DBData] objectAtIndex:[appDelegate currentMemoRowIndex]];

    

    self.tfTitle.text = [self.mData mTitle];

    self.tvContent.text = [self.mData mContent];

    self.tvContent.font = [UIFont fontWithName:@"Helvetica" size:12.0];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


posted by 프띠버리 2013. 10. 7. 15:24


ViewController.h


#import <UIKit/UIKit.h>


@interface ViewController : UIViewController


@property(nonatomic, strong) IBOutlet UIImageView *myImageView;


@end






ViewController.m




#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController

@synthesize myImageView;


- (BOOL)canBecomeFirstResponder

{

    return YES;

}


- (void)viewDidAppear:(BOOL)animated

{

    [self becomeFirstResponder];

}


// 흔들기 시작할 호출됨

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event

{

    [self.myImageView setImage:[UIImage imageNamed:@"dice.png"]];

}


// 흔들기 마칠 호출함

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event

{

    NSString *str = [NSString stringWithFormat:@"dice%d.png", arc4random()%6+1];

    [self.myImageView setImage:[UIImage imageNamed:str]];

}


- (void)viewDidLoad

{

    random();

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


posted by 프띠버리 2013. 10. 7. 14:52

AppDelegate.h


#import <UIKit/UIKit.h>


@interface AppDelegate : UIResponder <UIApplicationDelegate>

{

    UIWindow *window;

    UINavigationController *navigationController;

    

    NSString *databaseName;

    NSString *databasePath;

    

    NSMutableArray *foods;

}


@property (strong, nonatomic) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@property (nonatomic, retain) NSMutableArray *foods;


@end





AppDelegate.m


#import "AppDelegate.h"

#import "RootViewController.h"

#import "Food.h"

#import <sqlite3.h>


@implementation AppDelegate

@synthesize window;

@synthesize navigationController;

@synthesize foods;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

  

    RootViewController *mainViewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];

    self.navigationController = [[UINavigationController alloc] initWithRootViewController:mainViewController];

    databaseName = @"Basic.db";

    

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDir = [documentPaths objectAtIndex:0];

    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

    

    NSLog(@"%@", databasePath);

    

    [self checkAndCreateDatabase];

    

    [self readFoodsFromDatabase];

    

    [window addSubview:[navigationController view]];

    [window makeKeyAndVisible];

    return YES;

}


- (void)checkAndCreateDatabase

{

    BOOL success;

    NSFileManager *fileManager = [NSFileManager defaultManager];

    

    success = [fileManager fileExistsAtPath:databasePath];

    

    NSLog(@"error-1-");

    

    if(success) return;

    

    NSLog(@"error-2-");

    

    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

    

    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

}


- (void)readFoodsFromDatabase

{

    sqlite3 *database;

    

    foods = [[NSMutableArray alloc] init];

    

    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)

    {

        const char *sqlStatement = "select * from BasicTbl";

        sqlite3_stmt *compiledStatement;

        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)

        {

            while(sqlite3_step(compiledStatement) == SQLITE_ROW)

            {

                NSString *addr_MOBILE = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];

                NSString *addr_NAME = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];

                NSString *addr_ADDR = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];

                NSString *addr_TEL = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

                Food *food = [[Food alloc] initWithName:addr_NAME addr:addr_ADDR tel:addr_TEL mobile:addr_MOBILE];

                

                NSLog(@"error-3-, %@", addr_NAME);

                [foods addObject:food];

            }

        }

        sqlite3_finalize(compiledStatement);

    }

    sqlite3_close(database);

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell==nil)

    {

        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        

    }

    NSDictionary *dict = [foods objectAtIndex:indexPath.row];

    cell.textLabel.text = [dict objectForKey:@"name"];

    

    return cell;

}


@end





Food.h


#import <Foundation/Foundation.h>


@interface Food : NSObject

{

    NSString *name;

    NSString *addr;

    NSString *tel;

    NSString *mobile;

}



@property(nonatomic, retain) NSString *name;

@property(nonatomic, retain) NSString *addr;

@property(nonatomic, retain) NSString *tel;

@property(nonatomic, retain) NSString *mobile;


- (id)initWithName:(NSString *)n addr:(NSString *)a tel:(NSString *)t mobile:(NSString *)m;


@end





Food.m


#import "Food.h"


@implementation Food

@synthesize name, addr, tel, mobile;


- (id)initWithName:(NSString *)n addr:(NSString *)a tel:(NSString *)t mobile:(NSString *)m

{

    self.name = n;

    self.addr = a;

    self.tel = t;

    self.mobile = m;

        

    return self;

}


@end




FoodViewController.h


#import <UIKit/UIKit.h>


@interface FoodViewController : UIViewController

{

    IBOutlet UITextView *addrName;

    IBOutlet UITextView *addrAddr;

    IBOutlet UITextView *addrTel;

    IBOutlet UITextView *addrMobile;

}


@property (nonatomic, retain) IBOutlet UITextView *addrName;

@property (nonatomic, retain) IBOutlet UITextView *addrAddr;

@property (nonatomic, retain) IBOutlet UITextView *addrTel;

@property (nonatomic, retain) IBOutlet UITextView *addrMobile;



@end




FoodViewController.m


#import "FoodViewController.h"


@interface FoodViewController ()


@end


@implementation FoodViewController

@synthesize addrAddr, addrMobile, addrName, addrTel;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end






RootViewController.h


#import <UIKit/UIKit.h>

#import "FoodViewController.h"


@interface RootViewController : UITableViewController

{

    FoodViewController *foodView;

}


@property(nonatomic, retain) FoodViewController *foodView;


@end





RootViewController.m


#import "RootViewController.h"

#import "AppDelegate.h"

#import "Food.h"


@interface RootViewController ()


@end


@implementation RootViewController

@synthesize foodView;


- (id)initWithStyle:(UITableViewStyle)style

{

    self = [super initWithStyle:style];

    if (self) {

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];


    self.title = @"주소록";

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

}


#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

 

    return 1;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

  

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];

    return appDelegate.foods.count;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    

   

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    Food *food = (Food *)[appDelegate.foods objectAtIndex:indexPath.row];

    [cell.textLabel setText:food.name];

    

    return cell;

}

#pragma mark - Table view delegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    Food *food = (Food *)[appDelegate.foods objectAtIndex:indexPath.row];

    

    if(self.foodView == nil)

    {

        FoodViewController *viewController = [[FoodViewController alloc] initWithNibName:@"FoodViewController" bundle:nil];

        self.foodView = viewController;

    }

    [self.navigationController pushViewController:self.foodView animated:YES];

    

    self.foodView.title = [food name];

    

    [self.foodView.addrName setText:[food name]];

    [self.foodView.addrAddr setText:[food addr]];

    [self.foodView.addrTel setText:[food tel]];

    [self.foodView.addrMobile setText:[food mobile]];

    

}


@end


'Programing > IOS' 카테고리의 다른 글

DB를 이용한 간단 메모장 앱  (0) 2013.10.14
간단한 흔들기 제스쳐  (0) 2013.10.07
세그먼트 연습  (0) 2013.10.04
구구단 퀴즈 프로그램 앱  (0) 2013.10.04
선, 사각형 등 도형 그리기 연습  (0) 2013.10.04
posted by 프띠버리 2013. 10. 4. 17:20

ViewController.h


#import <UIKit/UIKit.h>


@interface ViewController : UIViewController


@end





ViewController.m


#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    

    // 배경색 변경

    [self.view setBackgroundColor:[UIColor whiteColor]];

    

    // 타이틀 배열 생성

    NSArray * title = [NSArray arrayWithObjects:@"RED", @"GREEN", @"BLUE", nil];

    

    // Bar Style

    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:title];

    [segment setFrame:CGRectMake(10, 70, 300, 30)];

    [segment setSegmentedControlStyle:UISegmentedControlStyleBar];

    [self.view addSubview:segment];


    // Bezeled Style

    UISegmentedControl *segment2 = [[UISegmentedControl alloc] initWithItems:title];

    [segment2 setFrame:CGRectMake(10, 70+100, 300, 30)];

    [segment2 setSegmentedControlStyle:UISegmentedControlStyleBezeled];

    [self.view addSubview:segment2];

    

    // Bordered Style

    UISegmentedControl *segment3 = [[UISegmentedControl alloc] initWithItems:title];

    [segment3 setFrame:CGRectMake(10, 70+100*2, 300, 30)];

    [segment3 setSegmentedControlStyle:UISegmentedControlStyleBordered];

    [self.view addSubview:segment3];

    

    // Plain Style

    UISegmentedControl *segment4 = [[UISegmentedControl alloc] initWithItems:title];

    [segment4 setFrame:CGRectMake(10, 70+100*3, 300, 30)];

    [segment4 setSegmentedControlStyle:UISegmentedControlStylePlain];

    [self.view addSubview:segment4];



}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end



posted by 프띠버리 2013. 10. 4. 17:15

guguquizAppDelegate.h


#import <UIKit/UIKit.h>


@interface guguquizAppDelegate : UIResponder <UIApplicationDelegate>


@property (strong, nonatomic) IBOutlet UIWindow *window;

@property (strong, nonatomic) IBOutlet UITabBarController *tabController;


@end




guguquizAppDelegate.m


#import "guguquizAppDelegate.h"


@implementation guguquizAppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

//    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

//    // Override point for customization after application launch.

//    self.window.backgroundColor = [UIColor whiteColor];

    

    self.window.rootViewController = self.tabController;

    [self.window makeKeyAndVisible];

    return YES;

}




GugudnaListViewController.h


#import <UIKit/UIKit.h>


@interface GugudnaListViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>


@end




GugudnaListViewController.m


#import "GugudnaListViewController.h"


@interface GugudnaListViewController ()


@end


@implementation GugudnaListViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


#pragma  - UITableView handler

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return 9;

}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 9; // 단수 출력

}


-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{

    return [NSString stringWithFormat:@"%d ", section + 1];

}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    NSString *identify = @"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];

    if(cell == nil)

    {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identify];

    }

    

    cell.textLabel.text = [NSString stringWithFormat:@"%d x %d", (indexPath.section + 1), (indexPath.row + 1)];

    cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", (indexPath.section + 1) * (indexPath.row + 1)];

    

    return cell;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    self.title = @"구구단 리스트";

    // Do any additional setup after loading the view from its nib.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




StartQuizViewController.h


#import <UIKit/UIKit.h>


@interface StartQuizViewController : UIViewController


- (IBAction)onStart:(id)sender;


@end




StartQuizViewController.m


#import "StartQuizViewController.h"

#import "QuizViewController.h"


@interface StartQuizViewController ()


@end


@implementation StartQuizViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    self.title = @"구구단 퀴즈";

    // Do any additional setup after loading the view from its nib.

}


- (IBAction)onStart:(id)sender

{

    QuizViewController *viewController = [[QuizViewController alloc] initWithNibName:@"QuizViewController" bundle:nil];

    [self.navigationController pushViewController:viewController animated:YES];

    viewController.totalQuiz = 10;

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




QuizViewController.h


#import <UIKit/UIKit.h>


@class StartQuizViewController;

@interface QuizViewController : UIViewController

{

    UILabel *labelFirst;

    UILabel *labelSecond;

    UITextField *testAnswer;

    NSInteger numAnswer;

    StartQuizViewController *mainViewController;

}


@property NSInteger totalQuiz;

@property NSInteger correctAnswer;

@property NSInteger wrongAnswer;

@property (nonatomic, retain) IBOutlet UITextField *textAnswer;

@property (nonatomic, retain) IBOutlet UILabel *labelFirst;

@property (nonatomic, retain) IBOutlet UILabel *labelSecond;

@property (nonatomic, retain) IBOutlet UILabel *labelMark;


- (void)onCheckAnswerAndNext;

- (void)putTheQuiz;


@end




QuizViewController.m


#import "QuizViewController.h"

#import "ResultViewController.h"


@interface QuizViewController ()


@end


@implementation QuizViewController


@synthesize totalQuiz;

@synthesize correctAnswer;

@synthesize wrongAnswer;

@synthesize textAnswer;

@synthesize labelFirst;

@synthesize labelSecond;

@synthesize labelMark;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)putTheQuiz

{

    int gugu_1 = arc4random() % 8 + 1;

    int gugu_2 = arc4random() % 8 + 1;

    

    labelFirst.text = [NSString stringWithFormat:@"%d", gugu_1];

    labelSecond.text = [NSString stringWithFormat:@"%d", gugu_2];

    

    numAnswer = gugu_1 * gugu_2;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

    

    [self putTheQuiz];

    [self.textAnswer becomeFirstResponder];

    

    // next button

    UIBarButtonItem *nextButton = [[UIBarButtonItem alloc] initWithTitle:@"다음" style:UIBarButtonItemStyleDone target:self action:@selector(onCheckAnswerAndNext)];

    self.navigationItem.rightBarButtonItem = nextButton;


    self.title = [NSString stringWithFormat:@"문제 %d", self.correctAnswer + self.wrongAnswer + 1];

}


- (void)viewDidAppear:(BOOL)animated

{

    NSMutableArray *views = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];

    

    if([views count] > 1 && [[views objectAtIndex:[views count] -2] isKindOfClass:[QuizViewController class]])

    {

        // 이전 QuizViewController 제거한다.

        [views removeObjectAtIndex:[views count] - 2];

        self.navigationController.viewControllers = views;

    }

}



- (void)onCheckAnswerAndNext

{

    if([textAnswer.text intValue] == numAnswer)

    {

        self.correctAnswer++;

        self.labelMark.text = @"O";

        

    }

    else

    {

        self.wrongAnswer++;

        [labelMark setTextColor:[UIColor redColor]];

        self.labelMark.text = @"X";

    }

    

    // animation

    self.labelMark.hidden = NO;

    self.labelMark.alpha = 0.0f;

    [UIView animateWithDuration:0.5f animations:^{self.labelMark.alpha = 1.0f;} completion:^(BOOL finished)

     {

         //화면전환

         if(self.totalQuiz == self.correctAnswer + self.wrongAnswer)

         {

             ResultViewController *viewController = [[ResultViewController alloc] initWithNibName:@"ResultViewController" bundle:nil];

             viewController.totalQuiz = self.totalQuiz;

             viewController.correctAnswer = self.correctAnswer;

             [self.navigationController pushViewController:viewController animated:YES];

         }

         else

         {

             QuizViewController *viewController = [[QuizViewController alloc] initWithNibName:@"QuizViewController" bundle:nil];

             viewController.totalQuiz = self.totalQuiz;

             viewController.correctAnswer = self.correctAnswer;

             viewController.wrongAnswer = self.wrongAnswer;

             [self.navigationController pushViewController:viewController animated:YES];

         }

         self.title = @"구구단 퀴즈";

     }];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




ResultViewController.h


#import <UIKit/UIKit.h>


@interface ResultViewController : UIViewController


@property NSInteger totalQuiz;

@property NSInteger correctAnswer;


@property (retain, nonatomic) IBOutlet UILabel *labelTotalQuiz;

@property (retain, nonatomic) IBOutlet UILabel *labelCorrectAnswer;

@property (retain, nonatomic) IBOutlet UILabel *labelMessage;


@end




ResultViewController.m


#import "ResultViewController.h"

#import "QuizViewController.h"


@interface ResultViewController ()


@end


@implementation ResultViewController

@synthesize totalQuiz;

@synthesize correctAnswer;

@synthesize labelTotalQuiz;

@synthesize labelCorrectAnswer;

@synthesize labelMessage;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

    

    self.labelTotalQuiz.text = [NSString stringWithFormat:@"%d", self.totalQuiz];

    self.labelCorrectAnswer.text = [NSString stringWithFormat:@"%d", self.correctAnswer];

    NSString *message = @"";

    float score = (float)correctAnswer / (float)totalQuiz * 100.0f;

    

    if(score == 100.0)

    {

        message = @" 잘했어요. ";

    }

    else if(score > 80.0f)

    {

        message = @"잘했어요. ";

    }

    else if(score > 60.0f)

    {

        message = @"노력 하셔야 겠네요. ";

    }

    else if(score > 40.0f)

    {

        message = @"부모님이 걱정하십니다. ";

    }

    else if(score > 20.0f)

    {

        message = @"아직 희망이 있어요. ";

    }

    else

    {

        message = @"이를 어쩌나... ";

    }

    self.labelMessage.text = message;

}


- (void)viewDidAppear:(BOOL)animated

{

    NSMutableArray *views = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];

    if([views count] > 1 && [[views objectAtIndex:[views count] - 2] isKindOfClass:[QuizViewController class]])

    {

        // 이전 QuizViewController 제거한다.

        [views removeObjectAtIndex:[views count] - 2];

        self.navigationController.viewControllers = views;

    }

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


posted by 프띠버리 2013. 10. 4. 17:04

draw.h


#import <UIKit/UIKit.h>


@interface draw : UIView

@property(nonatomic, strong) IBOutlet UISegmentedControl *seg;

@property(nonatomic) CGLineJoin lineJoinStyle;


- (void)setLineDash:(const CGFloat *)pattern count:(NSInteger)count phase:(CGFloat)phase;




@end




draw.m


#import "draw.h"


@implementation draw

@synthesize seg;


- (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        // Initialization code

    }

    return self;

}


- (void)drawRect:(CGRect)rect

{

    

//    // Drawing code

//    if(seg.selectedSegmentIndex == 0)

//    {

//        [self line];

//        NSLog(@" 선택");

//    }


    [self rectangle];

}


- (void)line

{

    // 빨강 직선

    UIBezierPath *path;

    path = [UIBezierPath bezierPath];

    [path setLineWidth:6.0];

    [path moveToPoint:CGPointMake(20, 50)];

    [path setLineCapStyle:kCGLineCapButt];

    [path addLineToPoint:CGPointMake(280, 50)];

    [[UIColor redColor] setStroke];

    [path stroke];


    // 녹색 직전

    UIBezierPath *path2;

    path2 = [UIBezierPath bezierPath];

    [path2 setLineWidth:6.0];

    [path2 moveToPoint:CGPointMake(20, 80)];

    [path2 setLineCapStyle:kCGLineCapSquare];

    [path2 addLineToPoint:CGPointMake(280, 80)];

    [[UIColor greenColor] setStroke];

    [path2 stroke];

    

    // 파란 점선

    UIBezierPath *path3;

    path3 = [UIBezierPath bezierPath];

    CGFloat pattern[]={10, 20, 30, 0};

    [path3 setLineDash:pattern count:4 phase:0];

    [path3 setLineWidth:6.0];

    [path3 moveToPoint:CGPointMake(20, 110)];

    [path3 setLineCapStyle:kCGLineCapButt];

    [path3 addLineToPoint:CGPointMake(280, 110)];

    [[UIColor blueColor] setStroke];

    [path3 stroke];

    

    // 모서리 둥근 직선

    UIBezierPath *path4;

    path4 = [UIBezierPath bezierPath];

    [path4 setLineWidth:20.0];

    [path4 moveToPoint:CGPointMake(20, 140)];

    [path4 setLineCapStyle:kCGLineCapRound];

    [path4 addLineToPoint:CGPointMake(280, 140)];

    [[UIColor whiteColor] setStroke];

    [path4 stroke];

    

    // 꺽인 직선

    UIBezierPath *path5;

    path5 = [UIBezierPath bezierPath];

    [path5 setLineWidth:20.0];

    [path5 moveToPoint:CGPointMake(20, 290)];

    [path5 setLineCapStyle:kCGLineCapButt];

    [path5 addLineToPoint:CGPointMake(150, 180)];

    [path5 addLineToPoint:CGPointMake(280, 290)];

    [[UIColor whiteColor] setStroke];

    [path5 stroke];

    

    // 꺽인 둥근 모서리 직선

    UIBezierPath *path6;

    path6 = [UIBezierPath bezierPath];

    [path6 setLineWidth:20.0];

    [path6 moveToPoint:CGPointMake(20, 360)];

    [path6 setLineCapStyle:kCGLineCapRound];

    [path6 addLineToPoint:CGPointMake(150, 250)];

    [path6 addLineToPoint:CGPointMake(280, 360)];

    [[UIColor whiteColor] setStroke];

    [path6 stroke];

    

    // 꺽인 직선

    UIBezierPath *path7;

    path7 = [UIBezierPath bezierPath];

    [path7 setLineWidth:20.0];

    [path7 moveToPoint:CGPointMake(20, 430)];

    [path7 setLineCapStyle:kCGLineCapSquare];

    [path7 addLineToPoint:CGPointMake(150, 320)];

    [path7 addLineToPoint:CGPointMake(280, 430)];

    [[UIColor whiteColor] setStroke];

    [path7 stroke];


}


- (void)rectangle

{

    UIBezierPath *path1;

    path1 = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(50, 320, 220, 90) cornerRadius:20];

    [[UIColor magentaColor] setStroke];

    [[UIColor orangeColor] setFill];

    [path1 fill];

    [path1 stroke];

    

    UIBezierPath *path2;

    path2 = [UIBezierPath bezierPathWithRect:CGRectMake(10, 50, 300, 400)];

    [[UIColor whiteColor] setStroke];

    [path2 setLineWidth:5.0];

    [path2 stroke];

    

    UIBezierPath *path3;

    path3 = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(30, 70, 260, 360) cornerRadius:5];

    [[UIColor whiteColor] setStroke];

    [path3 setLineWidth:5.0];

    [path3 stroke];


}


- (void)setLineDash:(const CGFloat *)pattern count:(NSInteger)count phase:(CGFloat)phase

{


}


@end


posted by 프띠버리 2013. 10. 1. 15:59



헤더화일 혹은 m파일 상단에 선언


// 타이머 변수 선언

NSTimer *timer;

// 시간흐름용 정수

int time;



m 파일에서 코딩하기


// 호출용 메소드 만들기

- (void)timePlus

{

    // 시간흐름용 변수에 메소드가 호출될때마다 1 증가

    time++;

    // 시간을 찍어줄 레이블 생성

    UILabel *timeLabel2 = [[UILabel alloc]init];

    timeLabel2.frame = CGRectMake(255105020);

    // 시간을 레이블에 표시할때 분과  형식으로 보여줌

    timeLabel2.text = [NSString stringWithFormat:@"%02d:%02d", (time/60)%60time%60];

    timeLabel2.font = [UIFont systemFontOfSize:15.0];

    // 시간을 화면에 표시

    [self.view addSubview:timeLabel2];

}



// 처음 화면 보여줄때(viewdidload부분에 추가해야 할 부분)


    // 타이머 변수에 timePlus메소드를 호출하여 1초간격으로 반복하게 

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timePlus) userInfo:nil repeats:YES];

    // 시간흐름용 변수의 초기값은 0

    time = 0;



우측 상단에 00:00으로 시작하는 시간표시 소스입니다.

시간흐르는 앱 만들때 참고하시라고 올립니다.

timeLabel2.text = [NSString stringWithFormat:@"%02d:%02d", (time/60)%60time%60];

부분이 시간표시하는 부분이니 만드는 방식에 따라 시간, 분, 초 등으로 코딩 가능합니다.



posted by 프띠버리 2013. 9. 30. 17:44

ViewController.h


#import <UIKit/UIKit.h>

#import <sqlite3.h>


@interface ViewController : UIViewController


@property(nonatomicsqlite3 *contactDB;

@property(strongnonatomicNSString *databasePath;

@property(strongnonatomicIBOutlet UITextField *name;

@property(strongnonatomicIBOutlet UITextField *address;

@property(strongnonatomicIBOutlet UITextField *phone;

@property(strongnonatomicIBOutlet UITextField *email;

@property(strongnonatomicIBOutlet UILabel *status;


- (IBAction)saveData;

- (IBAction)findContact;

- (IBAction)updateData;

- (IBAction)deleteData;


@end




ViewController.m

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController

@synthesize name, address, phone, status, databasePath, email, contactDB;


// 조회

- (void)findContact

{

    const char *dbpath = [databasePath UTF8String];

    sqlite3_stmt *statement;

    

    if(sqlite3_open(dbpath, &contactDB) == SQLITE_OK)

    {

        NSString *querySQL = [NSString stringWithFormat:@"SELECT address, phone, email FROM contacts WHERE name=\"%@\""name.text];

        

        const char *query_stmt = [querySQL UTF8String];

        

        if(sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)

        {

            if(sqlite3_step(statement) == SQLITE_ROW)

            {

                NSString *addressField = [[NSString allocinitWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];

                address.text = addressField;

                

                NSString *phoneField = [[NSString allocinitWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];

                phone.text = phoneField;

                

                NSString *emailField = [[NSString allocinitWithUTF8String:(const char *) sqlite3_column_text(statement, 2)];

                email.text = emailField;

                

                status.text = @"Match found";

            }

            else

            {

                status.text = @"Match not found";

                address.text = @"";

                phone.text = @"";

                email.text = @"";

            }

            sqlite3_finalize(statement);

        }

        sqlite3_close(contactDB);

    }

    

}


// 삭제

- (void)deleteData

{

    const char *dbpath = [databasePath UTF8String];

    sqlite3_stmt *statement;

    

    if(sqlite3_open(dbpath, &contactDB) == SQLITE_OK)

    {

        NSString *querySQL = [NSString stringWithFormat:@"DELETE from contacts where name=\"%@\""name.text];


        const char *query_stmt = [querySQL UTF8String];

        

        sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL);

    

        if(sqlite3_step(statement) == SQLITE_DONE)

        {

            status.text = @"Delete Data";

            name.text = @"";

            address.text = @"";

            phone.text = @"";

            email.text = @"";

        }

        else

        {

            status.text = @"Failed to del contact";

        }

        sqlite3_finalize(statement);

        sqlite3_close(contactDB);

    }

}


// 수정

- (void)updateData

{

    const char *dbpath = [databasePath UTF8String];

    sqlite3_stmt *statement;

    

    if(sqlite3_open(dbpath, &contactDB) == SQLITE_OK)

    {

        NSString *querySQL = [NSString stringWithFormat:@"UPDATE contacts set phone=\"%@\", address=\"%@\", email=\"%@\" where name=\"%@\""phone.textaddress.textemail.textname.text];

        

        const char *query_stmt = [querySQL UTF8String];

        sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL);

        

        if(sqlite3_step(statement) == SQLITE_DONE)

        {

            status.text = @"Update Data";

            name.text = @"";

            address.text = @"";

            phone.text = @"";

            email.text = @"";

        }

        else

        {

            status.text = @"Failed to Update contact";

        }

        sqlite3_finalize(statement);

        sqlite3_close(contactDB);

    }


}


// 입력

- (void)saveData

{

    const char *dbpath = [databasePath UTF8String];

    sqlite3_stmt *statement;

    if(sqlite3_open(dbpath, &contactDB) == SQLITE_OK)

    {

        NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO CONTACTS(name, address, phone, email) VALUES(\"%@\",\"%@\",\"%@\",\"%@\")"name.textaddress.textphone.textemail.text];

        const char *insert_stmt = [insertSQL UTF8String];

        sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);

        

        if(sqlite3_step(statement) == SQLITE_DONE)

        {

            status.text = @"Contact added";

            name.text = @"";

            address.text = @"";

            phone.text = @"";

            email.text = @"";

        }

        else

        {

            status.text = @"Failed to add contact";

        }

        sqlite3_finalize(statement);

        sqlite3_close(contactDB);

    }

    

}


- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    NSString *docsDir;

    NSArray *dirPaths;

    

    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectoryNSUserDomainMaskYES);

    docsDir = [dirPaths objectAtIndex:0];

    

    databasePath = [[NSString allocinitWithString:[docsDir stringByAppendingPathComponent:@"foods.sql"]];

    NSFileManager *filemgr = [NSFileManager defaultManager];

    

    if([filemgr fileExistsAtPath:databasePath] == NO)

    {

        const char *dbpath = [databasePath UTF8String];

        

        if(sqlite3_open(dbpath, &contactDB) == SQLITE_OK)

        {

            char *errMsg;

            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT, EMAIL TEXT)";

            

            if(sqlite3_exec(contactDB, sql_stmt, NULLNULL, &errMsg) != SQLITE_OK)

            {

                status.text = @"Failed to create table";

            }

            sqlite3_close(contactDB);

        }

        else

        {

            status.text = @"Failed to open/create database";

        }

    }

    

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


posted by 프띠버리 2013. 9. 16. 16:04

BeautyOfKoreaAppDelegate.h

#import <UIKit/UIKit.h>


@interface BeautyOfKoreaAppDelegate : UIResponder <UIApplicationDelegate>

{

    UIWindow *window;

    UINavigationController *navigationController;

}


@property (strong, nonatomic) IBOutlet UIWindow *window;

@property (strong, nonatomic) IBOutlet UINavigationController *navigationController;


@end




BeautyOfKoreaAppDelegate.m

#import "BeautyOfKoreaAppDelegate.h"

#import "RootViewController.h"


@implementation BeautyOfKoreaAppDelegate


@synthesize window;

@synthesize navigationController;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

//    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Override point for customization after application launch.

//    self.window.backgroundColor = [UIColor whiteColor];

    [self.window addSubview:[navigationController view]];

    [self.window makeKeyAndVisible];

    return YES;

}




RootViewController.h

#import <UIKit/UIKit.h>


@class ContentViewController;

@interface RootViewController : UIViewController

{

    IBOutlet UIButton *btnMenu1;

    IBOutlet UIButton *btnMenu2;

    IBOutlet UIButton *btnMenu3;

    IBOutlet UIButton *btnMenu4;

    IBOutlet UIButton *btnMenu5;

    IBOutlet UIButton *btnMenu6;

    IBOutlet UIImageView *ivBackground;

    IBOutlet UIImageView *ivTitle;

    ContentViewController *contentViewController;

}


@property(nonatomic, retain) IBOutlet UIButton *btnMenu1;

@property(nonatomic, retain) IBOutlet UIButton *btnMenu2;

@property(nonatomic, retain) IBOutlet UIButton *btnMenu3;

@property(nonatomic, retain) IBOutlet UIButton *btnMenu4;

@property(nonatomic, retain) IBOutlet UIButton *btnMenu5;

@property(nonatomic, retain) IBOutlet UIButton *btnMenu6;

@property(nonatomic, retain) IBOutlet UIImageView *ivBackground;

@property(nonatomic, retain) IBOutlet UIImageView *ivTitle;


-(IBAction)btnMenu1Touched;

-(IBAction)btnMenu2Touched;

-(IBAction)btnMenu3Touched;

-(IBAction)btnMenu4Touched;

-(IBAction)btnMenu5Touched;

-(IBAction)btnMenu6Touched;


@end




RootViewController.m


#import "RootViewController.h"

#import "ContentViewController.h"

#import "MapViewController.h"


@interface RootViewController ()


@end


@implementation RootViewController

@synthesize btnMenu1;

@synthesize btnMenu2;

@synthesize btnMenu3;

@synthesize btnMenu4;

@synthesize btnMenu5;

@synthesize btnMenu6;

@synthesize ivBackground;

@synthesize ivTitle;


-(IBAction)btnMenu1Touched

{

    contentViewController = [[ContentViewController alloc] initWithNibName:@"ContentViewController" bundle:nil];

    contentViewController.currentMenu = 1;

    [self.navigationController pushViewController:contentViewController animated:YES];

}


-(IBAction)btnMenu2Touched

{

    contentViewController = [[ContentViewController alloc] initWithNibName:@"ContentViewController" bundle:nil];

    contentViewController.currentMenu = 2;

    [self.navigationController pushViewController:contentViewController animated:YES];

    

}


-(IBAction)btnMenu3Touched

{

    contentViewController = [[ContentViewController alloc] initWithNibName:@"ContentViewController" bundle:nil];

    contentViewController.currentMenu = 3;

    [self.navigationController pushViewController:contentViewController animated:YES];

    

}


-(IBAction)btnMenu4Touched

{

    contentViewController = [[ContentViewController alloc] initWithNibName:@"ContentViewController" bundle:nil];

    contentViewController.currentMenu = 4;

    [self.navigationController pushViewController:contentViewController animated:YES];

    

}


-(IBAction)btnMenu5Touched

{

    contentViewController = [[ContentViewController alloc] initWithNibName:@"ContentViewController" bundle:nil];

    contentViewController.currentMenu = 5;

    [self.navigationController pushViewController:contentViewController animated:YES];

    

}


-(IBAction)btnMenu6Touched

{

    MapViewController *mapViewController = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:nil];

    [self.navigationController pushViewController:mapViewController animated:YES];

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




GalleryViewController.h

#import <UIKit/UIKit.h>


@interface GalleryViewController : UIViewController

{

    IBOutlet UIButton *btnBack;

    IBOutlet UIScrollView *svContent;

    int currentMenu;

}


@property(assign) int currentMenu;

@property(nonatomic, retain) IBOutlet UIButton *btnBack;

@property(nonatomic, retain) IBOutlet UIScrollView *svContent;


-(IBAction)btnbackTouched;


@end




GalleryViewController.m

#import "GalleryViewController.h"

//#import "ContentViewController.h"


#define kScrollObjHeight 466.0

#define kScrollObjWidth 310.0

#define kNumPhotos 20


@interface GalleryViewController ()


@end


@implementation GalleryViewController

@synthesize currentMenu;

@synthesize btnBack;

@synthesize svContent;


-(IBAction)btnbackTouched

{

    [self.navigationController popViewControllerAnimated:YES];

}


- (void)layoutScrollImages

{

    UIImageView *view = nil;

    NSArray *subviews = [svContent subviews];

    

    CGFloat curXLoc = 0;

    for(view in subviews)

    {

        if([view isKindOfClass:[UIImageView class]] && view.tag > 0)

        {

            CGRect frame = view.frame;

            frame.origin = CGPointMake(curXLoc, 0);

            view.frame = frame;

            

            curXLoc += (kScrollObjWidth);

        }

    }

    [svContent setContentSize:CGSizeMake((kNumPhotos * kScrollObjWidth), [svContent bounds].size.height)];

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

    

    svContent.clipsToBounds = YES;

    svContent.scrollEnabled = YES;

    svContent.directionalLockEnabled = YES;

    svContent.pagingEnabled = YES;

    

    for(int i=1;i<=kNumPhotos;i++)

    {

        NSString *imageName;

        

        if(i<10)

        {

            imageName = [NSString stringWithFormat:@"photos_%d_0%d.jpg", currentMenu, i];

        }

        else

        {

            imageName = [NSString stringWithFormat:@"phptos_%d_%d.jpg", currentMenu, i];

        }

        UIImage *image = [UIImage imageNamed:imageName];

        UIImageView *imageView =[[UIImageView alloc] initWithImage:image];

        

        CGRect rect = imageView.frame;

        rect.size.height = kScrollObjHeight;

        rect.size.width = kScrollObjWidth;

        imageView.frame = rect;

        imageView.tag = i;

        [svContent addSubview:imageView];

    }

    [self layoutScrollImages];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




MapViewController.h


#import <UIKit/UIKit.h>

#import <MapKit/MapKit.h>

#import "LocationAnnotation.h"


@interface MapViewController : UIViewController<MKMapViewDelegate>

{

    IBOutlet UIButton *btnBack;

    IBOutlet MKMapView *myMapView;

    IBOutlet UISegmentedControl *mapType;

    

    LocationAnnotation *locationAnnotation;

    

}


@property(nonatomic, readonly) LocationAnnotation *locationAnnotation;

@property(nonatomic, retain) IBOutlet UIButton *btnBack;

@property (strong, nonatomic) IBOutlet MKMapView *myMapView;

@property(strong, nonatomic) IBOutlet UISegmentedControl *mapType;


-(IBAction)btnBackTouched;

-(IBAction)mapTypeChanged;


@end




MapViewController.m


#import "MapViewController.h"

#import "ContentViewController.h"

#import <CoreLocation/CoreLocation.h>

#import <MapKit/MKUserLocation.h>

#import <CoreLocation/CLLocation.h>


@interface MapViewController ()


@end


@implementation MapViewController

@synthesize btnBack;

@synthesize myMapView;

@synthesize mapType;

@synthesize locationAnnotation;


-(IBAction)mapTypeChanged

{

    if(mapType.selectedSegmentIndex == 0)

    {

        myMapView.mapType = MKMapTypeStandard;

    }

    else if(mapType.selectedSegmentIndex==1)

    {

        myMapView.mapType = MKMapTypeSatellite;

    }

    else if(mapType.selectedSegmentIndex==2)

    {

        myMapView.mapType = MKMapTypeHybrid;

    }

}


-(IBAction)btnBackTouched

{

    [self.navigationController popViewControllerAnimated:YES];    

}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

        // Custom initialization

        [myMapView setShowsUserLocation:YES];

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

    myMapView.showsUserLocation = NO;

    myMapView.mapType = MKMapTypeStandard;

    myMapView.delegate = self;

    

    CLLocationCoordinate2D location;

    

    location.latitude = 35.815586;

    location.longitude = 129.333587;

    

    locationAnnotation = [[LocationAnnotation alloc] initWithCoordinate:location];

    [locationAnnotation setCurrentTitle:@"불국사(佛國寺)"];

    [locationAnnotation setCurrentSubTitle:@"Bulguksa Temple"];

    

    [myMapView addAnnotation:locationAnnotation];

    

    location.latitude = 36.543294;

    location.longitude = 128.553402;

    

    locationAnnotation = [[LocationAnnotation alloc] initWithCoordinate:location];

    [locationAnnotation setCurrentTitle:@"병산서원(倂山書院)"];

    [locationAnnotation setCurrentSubTitle:@"Byungsan Seowon"];

    

    [myMapView addAnnotation:locationAnnotation];

    

    location.latitude = 36.575835;

    location.longitude = 128.527465;


    locationAnnotation = [[LocationAnnotation alloc] initWithCoordinate:location];

    [locationAnnotation setCurrentTitle:@"하회마을"];

    [locationAnnotation setCurrentSubTitle:@"Hahoe Village"];

    

    [myMapView addAnnotation:locationAnnotation];

    

    location.latitude = 37.033255;

    location.longitude = 128.689513;


    locationAnnotation = [[LocationAnnotation alloc] initWithCoordinate:location];

    [locationAnnotation setCurrentTitle:@"부석사(浮石寺)"];

    [locationAnnotation setCurrentSubTitle:@"Busoksa Temple"];

    

    [myMapView addAnnotation:locationAnnotation];

    

    location.latitude = 35.838133;

    location.longitude = 129.219276;


    locationAnnotation = [[LocationAnnotation alloc] initWithCoordinate:location];

    [locationAnnotation setCurrentTitle:@"첨성대(瞻星臺)"];

    [locationAnnotation setCurrentSubTitle:@"Cheomseongdae"];

    

    [myMapView addAnnotation:locationAnnotation];

    

    location.latitude = 36.256861;

    location.longitude = 128.716908;

    

    MKCoordinateRegion region;

    MKCoordinateSpan span;

    span.latitudeDelta = 1;

    span.longitudeDelta = 1;

    

    region.span = span;

    region.center = location;

    

    [myMapView setRegion:region animated:YES];

    [myMapView regionThatFits:region];

}


- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation

{

    MKAnnotationView *annView=[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];

    annView.canShowCallout = YES;

    

    UIButton *btnDetailInfo = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

    btnDetailInfo.frame = CGRectMake(0, 0, 23, 23);

    btnDetailInfo.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

    btnDetailInfo.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

    

    annView.rightCalloutAccessoryView = btnDetailInfo;

    annView.image = [UIImage imageNamed:@"annotationIcon.png"];

    annView.canShowCallout = YES;

    

    return annView;

}


- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control

{

    LocationAnnotation *temp = view.annotation;

    

    NSString *tit1 = @"병산서원(倂山書院)";

    NSString *tit2 = @"불국사(佛國寺)";

    NSString *tit3 = @"부석사(浮石寺)";

    NSString *tit4 = @"첨성대(瞻星臺)";

    NSString *tit5 = @"하회마을";

    

    ContentViewController *contentViewController = [[ContentViewController alloc] initWithNibName:@"ContentViewController" bundle:nil];

    

    if(temp.title == tit1)

    {

        contentViewController.currentMenu = 1;

    }

    else if(temp.title == tit2)

    {

        contentViewController.currentMenu = 2;

    }

    else if(temp.title == tit3)

    {

        contentViewController.currentMenu = 3;

    }

    else if(temp.title == tit4)

    {

        contentViewController.currentMenu = 4;

    }

    else if(temp.title == tit5)

    {

        contentViewController.currentMenu = 5;

    }

    

    [self.navigationController pushViewController:contentViewController animated:YES];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




LocationAnnotation.h


#import <Foundation/Foundation.h>

#import <MapKit/MapKit.h>


@interface LocationAnnotation : NSObject <MKAnnotation>

{

    CLLocationCoordinate2D coordinate;

    

    NSString *currentSubTitle;

    NSString *currentTitle;

}


@property(nonatomic, readonly) CLLocationCoordinate2D coordinate;

@property(nonatomic, retain) NSString *currentTitle;

@property(nonatomic, retain) NSString *currentSubTitle;


- (NSString *)title;

- (NSString *)subtitle;


- (id)initWithCoordinate:(CLLocationCoordinate2D) c;


@end




LocationAnnotation.m

#import "LocationAnnotation.h"

#import <MapKit/MapKit.h>


@implementation LocationAnnotation


@synthesize coordinate;

@synthesize currentSubTitle;

@synthesize currentTitle;


- (NSString *)subtitle

{

    return currentSubTitle;

}


- (NSString *)title

{

    return currentTitle;

}


- (id)initWithCoordinate:(CLLocationCoordinate2D)c

{

    coordinate = c;

    return self;

}


@end