Mar
30

Базовые примеры и сценарии iPhone SDK. Часть 1

Еще одна статья от Алекса Краковецкого о разработке для iPhone.

Здесь представлены базовые примеры, с которыми приходиться сталкиваться практически каждый день программистам для iPhone.

Logging

Для того, чтобы увидеть логи, необходимо выбрать Run > Console в Xcode .

NSLog(@"log: %@ ", myString); // для переменных типа NSString
NSLog(@"log: %f ", myFloat); // для переменных типа float
NSLog(@"log: %i ", myInt); // для переменных типа int

Добавление изображения

CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:@"myImage.png"]];
myImage.opaque = YES;
[self.view addSubview:myImage];
[myImage release];

Добавление UIWebView

CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);
UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
[webView setBackgroundColor:[UIColor whiteColor]];
NSString *urlAddress = @"http://www.google.com";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj]; [self addSubview:webView];
[webView release];

Отображение статуса Network Activity

IApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES; // для остановки уставите значение в NO

Конвертация NSInteger в NSString

currentScoreLabel.text = [NSString stringWithFormat:@"%d", currentScore];

Подвижные (draggable) элементы

  1. Создаем новый класс который наследуется от UIImageView
    @interface myDraggableImage : UIImageView { }
  2. В реализации этого класса добавляем два метода:
    - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {               
        // Retrieve the touch point
        CGPoint pt = [[touches anyObject] locationInView:self];
        startLocation = pt;
        [[self superview] bringSubviewToFront:self];
    }
    - (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {               
        // Move relative to the original touch point
        CGPoint pt = [[touches anyObject] locationInView:self];
        CGRect frame = [self frame];
        frame.origin.x += pt.x - startLocation.x;
        frame.origin.y += pt.y - startLocation.y;
        [self setFrame:frame];
    }
    
  3. Создайте изображение (или то, что вам необходимо) и добавьте ее к вашему view:
    dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];
    [dragger setImage:[UIImage imageNamed:@"myImage.png"]];
    [dragger setUserInteractionEnabled:YES];
    

Потоки (Threading)

  1. Создайте новый поток:
    [NSThread detachNewThreadSelector:@selector(myMethod)  toTarget:self withObject:nil];
    
  2. Создайте новый метод, который указан в потоке:
    - (void)myMethod {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        // *** code that should be run in the new thread goes here ***
        [pool release];
    }
    

Таймеры

Таймер, который будет запускаться раз в секунду:

[NSTimer scheduledTimerWithTimeInterval:1       target:self selector:@selector(myMethod)   userInfo:nil    repeats:YES];

Если нужно передать какой то параметр в вашу функцию, необходимо использовать следующий код:

[NSTimer scheduledTimerWithTimeInterval:1       target:self selector:@selector(myMethod)   userInfo: myObject repeats:YES];

Далее создаете функцию, которая будет запускаться по таймеру:

-(void)myMethod:(NSTimer*)timer {
    // Now I can access all the properties and methods of myObject
    [[timer userInfo] myObjectMethod];
}

Останавливаем таймер:

[myTimer invalidate];
myTimer = nil; // ensures we never invalidate an already invalid Timer

Время

CFAbsoluteTime myCurrentTime = CFAbsoluteTimeGetCurrent();
// perform calculations here

Уведомления (Alerts)

Простейшое уведомление с кнопкой ОК:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"An Alert!"              delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

Определение Subview

Для этого небходимо использовать tag для views:

for (UIImageView *anImage in [self.view subviews]) {
    if (anImage.tag == 1)  {
        // do something
    }
}

Еще интересные посты о программировании для мобильных устройств:

No Comments

Make A Comment

No comments yet.

Comments RSS Feed   TrackBack URL

Leave a comment

Please leave these two fields as-is:
Ателье ремонта и пошива одежды: индивидуальный пошив обуви в москве. Индивидуальный пошив. ; ייצור מטבחים ; Интернет-магазин Знатная Дама предлагает купить брюки женские от производителя оптом и розницу. ; прогноз курса доллара евро ; презентация powerpoint обучение

top