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






posted by 프띠버리 2013. 9. 13. 16:56

TableViewController.h


#import <UIKit/UIKit.h>


@interface TableViewController : UITableViewController<UITableViewDataSource, UITableViewDelegate>

{

    NSArray *products;

}



@end




TableViewController.m


#import "TableViewController.h"


@interface TableViewController ()


@end


@implementation TableViewController

#define ITEM_NAME @"ITEM_NAME"

#define ITEM_PRICE @"ITEM_PRICE"

#define ITEM_PIC @"ITEM_PIC"

#define ITEM_ID @"ITEM_ID"


- (id)initWithStyle:(UITableViewStyle)style

{

    self = [super initWithStyle:style];

    if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

/*

    products = [[NSArray alloc] initWithObjects:

                [NSDictionary dictionaryWithObjectsAndKeys:@"0", ITEM_ID, @"iPAD", ITEM_NAME, @"699$", ITEM_PRICE, @"ipad2.jpg", ITEM_PIC, nil],

                [NSDictionary dictionaryWithObjectsAndKeys:@"1", ITEM_ID, @"iMAC", ITEM_NAME, @"1199$", ITEM_PRICE, @"imac.jpg", ITEM_PIC, nil],

                [NSDictionary dictionaryWithObjectsAndKeys:@"2", ITEM_ID, @"iPhone", ITEM_NAME, @"699$", ITEM_PRICE, @"iphone.jpg", ITEM_PIC, nil],

                [NSDictionary dictionaryWithObjectsAndKeys:@"3", ITEM_ID, @"MacBook", ITEM_NAME, @"699$", ITEM_PRICE, @"macbook.jpg", ITEM_PIC, nil],

                [NSDictionary dictionaryWithObjectsAndKeys:@"4", ITEM_ID, @"iPAD Nano", ITEM_NAME, @"149$", ITEM_PRICE, @"nano.jpg", ITEM_PIC, nil],

                nil];

 */

    products = @[@{ITEM_ID:@"0", ITEM_NAME:@"iPad", ITEM_PRICE:@"699$", ITEM_PIC:@"ipad2.jpg"},

                 @{ITEM_ID:@"1", ITEM_NAME:@"iMAC", ITEM_PRICE:@"1199$", ITEM_PIC:@"imac.jpg"},

                 @{ITEM_ID:@"2", ITEM_NAME:@"iPhone", ITEM_PRICE:@"699$", ITEM_PIC:@"iphone.jpg"},

                 @{ITEM_ID:@"3", ITEM_NAME:@"MacBook", ITEM_PRICE:@"999$", ITEM_PIC:@"macbook.jpg"},

                 @{ITEM_ID:@"4", ITEM_NAME:@"iPad Nano", ITEM_PRICE:@"149$", ITEM_PIC:@"nano.jpg"}];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    // Return the number of sections.

    return 1;

}


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

{

    // Return the number of rows in the section.

    return [products count];

}


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

{

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    

    // Configure the cell...

    if(cell==nil)

    {

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

    }

    NSDictionary *productInfo=[products objectAtIndex:indexPath.row];

    NSString *name=[productInfo objectForKey:ITEM_NAME];

    NSString *price=[productInfo objectForKey:ITEM_PRICE];

    NSString *pic=[productInfo objectForKey:ITEM_PIC];

    

    UIImageView *picView=(UIImageView *)[cell viewWithTag:100];

    picView.image = [UIImage imageNamed:pic];

    

    UILabel *nameLabel=(UILabel *)[cell viewWithTag:200];

    nameLabel.text = name;

    

    UILabel *priceLabel = (UILabel *)[cell viewWithTag:300];

    priceLabel.text = price;

    

    return cell;

}



@end



TablePrice4.zip


posted by 프띠버리 2013. 9. 11. 06:54

 

 

ViewController.h


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate>

{

    // 텍스트 필드 변수 선언

    IBOutlet UITextField *contextTextField;

    // 테이블용 변수 선언

    IBOutlet UITableView *table;

    // 유동성 배열 변수 선언

    NSMutableArray *data;

    // url저장할 문자열 변수 선언

    NSString *urlStr;

}

// 웹뷰용 변수 선언

@property (weak, nonatomic) IBOutlet UIWebView *webView;

 

// 테이블에 셀의 내용 추가할 메소드
- (IBAction)addItem:(id)sender;

// 테이블 수정 모드로 전환할때 메소드

- (IBAction)toggleEditMode:(id)sender;



@end



ViewController.m

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController

// 섹션구분을 위해 CELL_ID란 이름을 정의

#define CELL_ID @"CELL_ID"

 

// 테이블의 섹션 개수

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    // 섹션 개수는 1개

    return 1;

}

 

// 테이블 섹션의 셀 개수

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

{

    // 셀 개수는 data라는 배열안의 개수 만큼 표시

    return [data count];

}

 

// 테이블의 내용이 있는 셀을 선택했을때
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    // urlStr이라는 문자열 변수에 현재 선택한 셀의 텍스트를 저장한다.

    urlStr = [data objectAtIndex:indexPath.row];

    NSLog(@"%@", urlStr);

    // url형식을 가지는 변수에 urlStr의 내용을 넣어서 웹뷰에서 쓸수 있게 한다.

    NSURL *url = [NSURL URLWithString:urlStr];

    // 웹뷰의 URL에 url변수의 주소를 집어 넣음

    NSURLRequest *requestURL = [NSURLRequest requestWithURL:url];

    // 웹뷰에 현재 url이 가리키는 주소의 웹페이지를 화면에 보여준다.

    [self.webView loadRequest:requestURL];

    

}

 

// 테이블 셀 안에 내용 집어넣기

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

{

    // cell은 CELL_ID라는 이름을 가지는 테이블 셀형식이다.

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_ID];

    // 표시할 내용을 가진 셀이 없으면

    if(nil == cell)

    {

        // cell은 CELL_ID라는 이름을 가진 기본 형태의 셀로 초기화됨

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

    }

    // 각 셀의 텍스는 data라는 배열안의 내용을 넣어준다. 

    cell.textLabel.text = [data objectAtIndex:indexPath.row];

    // 셀을 반환하여 각 셀이 내용을 가지게 된다.

    return cell;

}


// 수정

- (void)tableView:(UITableView *)tableview commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

    // 테이블이 수정(셀 지우기) 모드일때

    if(editingStyle == UITableViewCellEditingStyleDelete)

    {

        // data배열에서 현재 선택된 셀의 내용을 지움

        [data removeObjectAtIndex:indexPath.row];

        // 테이블 다시 보여주기

        [table reloadData];

    }

}


// 이동

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath

{

    // 셀이 하나 지워지면 위치를 이동한다.

    return YES;

}


// 이동 -> 데이터 적용(좀더 이해가 필요함)

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath

{

    // 오브젝트형 obj변수에 data 배열의 현재 선택된 부분 저장

    NSObject *obj = [data objectAtIndex:sourceIndexPath.row];

    // data 배열에서 현재 선택된 부분 삭제

    [data removeObjectAtIndex:sourceIndexPath.row];

    // data 배열에 obj에 저장된 내용을 삽입

    [data insertObject:obj atIndex:destinationIndexPath.row];

    NSLog(@"data : %@", data);

}


// 키보드

- (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    // 기본적으로 프로그램이 실행되면 포커스는 텍스트 필드에 맞춰짐

    [textField resignFirstResponder];

    // additem메소드 호출

    [self addItem:nil];

    // 키패드 자동으로 내려가기

    return YES;

}


- (void)viewDidLoad

{

    [super viewDidLoad];

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

    // 웹뷰 델리게이트

    self.webView.delegate = self;

    // 텍스트필드 델리게이트

    contextTextField.delegate = self;

    // data를 유동형 배열로 초기화

    data = [[NSMutableArray alloc] init];

}


// 데이터 추가

- (IBAction)addItem:(id)sender

{

    // 문자열 변수 inputStr은 현재 입력된 텍스트 필드의 내용을 저장한다.

    NSString *inputStr = contextTextField.text;

    // inputStr 문자열의 길이가 0 보다 클때만(즉, 하나의 내용이라도 들어가 있을때만)

    if([inputStr length] > 0)

    {

        // data 배열에 현재 택스트 필드에 입력했던 내용을 추가

        [data addObject:inputStr];

        // 테이블 다시보여주기

        [table reloadData];

        // 텍스프 필드 공란으로 초기화

        contextTextField.text = @"";

    }

}


// 편집/완료 상태 토글식 동작

- (IBAction)toggleEditMode:(id)sender

{

    // 테이블이 수정모드면 비수정 상태로

    table.editing = !table.editing;

    // 버튼의 제목은 수정모드일때 Done를 표시 아니면 Edit를 표시

    ((UIBarButtonItem *)sender).title = table.editing ? @"Done" : @"Edit";

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end




 

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

뷰티 오브 코리아 앱 소스  (0) 2013.09.16
테이블 셀 커스텀 디자인  (0) 2013.09.13
카드 짝 맞추기 게임  (0) 2013.08.29
Slider 및 TextField 및 OnOff 스위치 연습  (0) 2013.08.26
TableView 연습 코딩  (0) 2013.08.26
posted by 프띠버리 2013. 8. 29. 12:49



ViewController.h

#import <UIKit/UIKit.h>


@interface ViewController : UIViewController

{

    UIButton *prevBtn;              // 이전 버튼

    UILabel *life;                  // 생명 텍스트

}


// 현재 버튼

@property(strongnonatomicUIButton *button;

// 카드 앞면 들어갈 배열

@property(strongnonatomicNSMutableArray *frontCard;


// 액션 메소드(프로그램에서 클릭시 구동되는 시작 메소드)

- (IBAction)action:(id)sender;


@end





ViewController.m

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController

@synthesize button;             // 지금 버튼 선언

@synthesize frontCard;          // 카드 배열 선언

int count;                      // 카드 클릭 카운터 변수 선언

int chkImg;                     // 이전 클릭된 이미지를 정수로 입력받을 변수 선언

int succes;                     // 성공 횟수 변수 선언

int intvalCount;                // 오버 횟수 클릭시 처리할 변수 선언

int fail;                       // 실패 횟수 변수 선언


// 초기 화면

- (void)viewDidLoad

{

    // 초기화 메소드 불러오기

    [self initScreen];

    

    [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.

}


// 초기화 메소드

-(void)initScreen

{

    // 화면 전체 클리어

    for(UIView *subview in [self.view subviews])

    {

         [subview removeFromSuperview];

    }

    

    // 버튼을 그리기 위한 for문용 변수 i, j  생성되는 버튼에 태그숫자를 붙여줄 변수 선언

    int i, j, tagNum;


    //  변수 초기화

    succes = 0;

    intvalCount = 0;

    fail = 0;

    count = 0;

    chkImg = 0;

    

    // 유동성 배열을 생성하여 초기 값을 집어 넣음

    frontCard = [[NSMutableArray allocinitWithObjects:@"1"@"1"@"2"@"2"@"3"@"3"@"4"@"4"@"5"@"5"@"6"@"6"@"7"@"7"@"8"@"8"nil];

    

    // 유동성 배열의 내용을 섞어 주는 메소드 호출

    [self shuffle];

    

    // 버튼의 태그 수를 0으로 지정

    tagNum = 0;

    

    // 제일 상단 제목 레이블로 만들기

    UILabel *label = [[UILabel allocinit];            // label이란 레이블 변수 생성

    label.frame = CGRectMake(801516020);          // 가로 80 세로 15 위치에서 가로 160, 세로 20크기의 레이블 생성

    label.text = @"카드  맞추기 게임";                     // 레이블안에 들어갈 텍스트 내용

    label.font = [UIFont systemFontOfSize:20.0];        // 레이블에 적용된 텍스트의 크기

    [self.view addSubview:label];                       // 레이블 화면에 보여주기


    // 제일 하단에 생명 하트 표시를 레이블을 이용해 텍스트로 표시

    life = [[UILabel allocinit];

    life.frame = CGRectMake(1535030040);

    life.font = [UIFont systemFontOfSize:25];

    life.text = @"생명 : ♡ ♡ ♡ ♡ ♡ ♡ ♡ ♡";

    [self.view addSubview:life];


    // 16개의 버튼 생성 하기

    for(i=0;i<4;i++)                        // 4줄로 만듬

    {

        for(j=0;j<4;j++)                    // 한줄에 4개씩 만듬

        {

            // 버튼에 이미지를 입히기 위해 커스텀 타입으로 생성

            button  = [UIButton buttonWithType:UIButtonTypeCustom];

            // 버튼의 위치를 for문을 이용하여 만듬

            button.frame = CGRectMake(15+(j*75), 50+(i*75), 6565);

            // 버튼이 생성될때 마다 태그의 값을 1 증가시킴

            tagNum += 1;

            // 버튼 태그의 값에 1 증가된 값을 집어 넣음

            button.tag = tagNum;

            // 버튼의 이미지는 backcard.jpg이고 효과는 없음

            [button setImage:[UIImage imageNamed:@"backcard.jpg"forState:UIControlStateNormal];

            // 버튼을 클릭시 sction:메소드를 실행

            [button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];

            // 버튼을 화면에 보여줌

            [self.view addSubview:button];

        }

    }

    

    // 개발자요 버튼 위치 확인 부분

    for(i=0;i<16;i++)

    {

        NSLog(@"%@"frontCard[i]);

    }

}


// Mutable 배열 섞기

int randomSort(id obj1, id obj2, void*context)

{

    return (arc4random()%3 - 1);

}


- (void)shuffle

{

    [frontCard sortUsingFunction:randomSort context:nil];

}

//------------ 여기까지 배열 섞기 고정 메소드


// 버튼 클릭시 호출 되는 action: 메소드

- (IBAction)action:(id)sender

{

    // 버튼의 클릭횟수가 2보다 작을때

    if(intvalCount < 2)

    {

        // 버튼의 태그값을 알랴줌

        button = sender;

        // 버튼의 태그값에 맞춰서 체크하는 메소드 호출

        [self checkCard];

        // 1초의 대기 시간동안 클릭횟수가 2 넘어가지 않으면 intvalCtn 메소드를 호출

        [self performSelector:@selector(intvalCtn) withObject:nil afterDelay:1.0];


    }

    // 버튼의 클릭횟수가 2이상이 된다면

    else

    {

        // 경고창 호출

        UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"경고" message:@"2번만 클릭 가능합니다" delegate:self cancelButtonTitle:@"확인" otherButtonTitles:nilnil];

        [alert show];

        // 클릭횟수 변수 초기화

        intvalCount = 0;

    }

    // 클릭횟수 변수 1증가

    intvalCount += 1;

}


// 버튼의 클릭횟수가 2 넘어가지 않을때 호출되는 메소드

- (void) intvalCtn

{

    // 클릭횟수 변수 초기화

    intvalCount = 0;

}


// 클릭한 카드 2개를 비교하여 같은지 아닌지  에러 부분 체크 하는 메소드

- (void) checkCard

{

    

    // 버튼 클릭시 뒤집어 질때 태그와 배열의 값에 맞춰서 앞면 이미지 표시

    NSString *imageName = [NSString stringWithFormat:@"frontcard0%@.jpg"frontCard[button.tag-1]];

    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];

    

    // 처음 버튼 클릭시

    if(count == 0)

    {

        // 이전 이미지용 변수에 지금 클릭된 이미지의 태그값에 해당하는 이미지 번호를 정수화 하여 저장

        chkImg = [frontCard[button.tag-1intValue];

        // 이전 버튼에 현재의 버튼을 저장

        prevBtn = button;

        // 두번째 클릭을 위해 카운터 1증가

        count = count + 1;

        // 뒤집힌 카드가 다시 클릭되는것을 방지하기 위해 현재의 버튼 비활성화

        button.enabled = NO;


    }

    // 두번째 버튼 클릭시

    else if(count == 1)

    {

        // 처음 카드와 두번째 카드의 이미지 번호가 같다면

        if([frontCard[button.tag-1intValue] == chkImg)

        {

            // 성공횟수 1증가

            succes = succes + 1;

            // 카드 클릭 카운터 변수 초기화

            count = 0;

            // 이제  카드가 클릭되면 안됨으로 둘다 비활성화

            prevBtn.enabled = NO;

            button.enabled = NO;

            

            // 모든 카드가  맞았을때

            if(succes == 8)

            {

                // 게임종료 경고창 호출

                UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"VICTORY" message:@"클리어를 축하합니다." delegate:self cancelButtonTitle:@"메인으로" otherButtonTitles:@"다시하기"nil];

                [alert show];

                // 성공 횟수 초기화

                succes = 0;

            }

        }

        // 처음 카드와 두번째 카드의 이미지 번호가 다르다면

        else

        {

            // 이전 버튼을 클릭할수 있도록 활성화

            prevBtn.enabled = YES;

            // 실패 횟수 증가

            fail = fail + 1;

            

            // 뒤집힌 카드를 확인 하기 위해 0.5초후에 다시 뒷면으로 뒤집히게 

            [self performSelector:@selector(delayImg) withObject:nil afterDelay:0.5];

            

            // 실패 횟수에 따른 하트 감소 레이블 텍스트 표시

            if(fail == 1)

            {

                life.text = @"";

                life.text = @"생명 : ♡ ♡ ♡ ♡ ♡ ♡ ♡";


            }

            else if(fail == 2)

            {

                life.text = @"";

                life.text = @"생명 : ♡ ♡ ♡ ♡ ♡ ♡";

            }

            else if(fail == 3)

            {

                life.text = @"";

                life.text = @"생명 : ♡ ♡ ♡ ♡ ♡";

            }

            else if(fail == 4)

            {

                life.text = @"";

                life.text = @"생명 : ♡ ♡ ♡ ♡";

            }

            else if(fail == 5)

            {

                life.text = @"";

                life.text = @"생명 : ♡ ♡ ♡";

            }

            else if(fail == 6)

            {

                life.text = @"";

                life.text = @"생명 : ♡ ♡";

            }

            else if(fail == 7)

            {

                life.text = @"";

                life.text = @"생명 : ♡";

            }

            // 하트가  떨어지면

            else if(fail == 8)

            {

                life.text = @"";

                

                // 게임 실패 경고창 호출

                UIAlertView *alert = [[UIAlertView allocinitWithTitle:@"LOSE" message:@"실패하였습니다." delegate:self cancelButtonTitle:@"메인으로" otherButtonTitles:@"다시하기"nil];

                [alert show];

                // 실패 횟수 0으로 초기화

                fail = 0;

            }

            

            //  클릭 카운터 변수 초기화

            count = 0;

        }

    }

}


// 0.5초후 뒷면 보여줄 메소드

- (void)delayImg

{

    // 이전 버튼의 이미지를 다시 뒷면이 되게 

    [prevBtn setImage:[UIImage imageNamed:@"backcard.jpg"forState:UIControlStateNormal];

    // 지금 버튼의 이미지를 다시 뒷면이 되게 

    [button setImage:[UIImage imageNamed:@"backcard.jpg"forState:UIControlStateNormal];

}


// 경고창 반응

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

{

    // 다시하기를 클릭했을때

    if(buttonIndex == alertView.firstOtherButtonIndex)

    {

        // 게임 내용 다시 초기화

        [self initScreen];

    }

}


@end