Добро пожаловать в новую главу нашего учебника по Objective-C! В этой главе мы познакомимся с основными компонентами iOS SDK и научимся работать с ними на практике. iOS SDK предоставляет множество инструментов и фреймворков для разработки мощных и функциональных приложений для iPhone и iPad. Мы рассмотрим наиболее часто используемые компоненты и покажем примеры их использования. Как всегда, мы объясним все простым и понятным языком, чтобы вы могли легко во всем разобраться.
Шаг 1: Создание проекта
Шаг 2: Настройка AppDelegate
// AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Создаем окно
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
// Создаем корневой ViewController
ViewController *rootViewController = [[ViewController alloc] init];
// Устанавливаем корневой ViewController
self.window.rootViewController = rootViewController;
// Делаем окно видимым
[self.window makeKeyAndVisible];
return YES;
}
@end
Шаг 3: Создание интерфейса в ViewController
// ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UILabel *myLabel;
@property (nonatomic, strong) UIButton *myButton;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Устанавливаем цвет фона
self.view.backgroundColor = [UIColor whiteColor];
// Создаем и настраиваем UILabel
self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 220, 40)];
self.myLabel.text = @"Привет, мир!";
self.myLabel.textAlignment = NSTextAlignmentCenter;
self.myLabel.textColor = [UIColor blackColor];
// Добавляем UILabel на View
[self.view addSubview:self.myLabel];
// Создаем и настраиваем UIButton
self.myButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.myButton.frame = CGRectMake(100, 200, 120, 40);
[self.myButton setTitle:@"Нажми меня" forState:UIControlStateNormal];
// Добавляем действие для кнопки
[self.myButton addTarget:self
action:@selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
// Добавляем UIButton на View
[self.view addSubview:self.myButton];
}
- (void)buttonPressed {
self.myLabel.text = @"Кнопка нажата!";
}
@end
Шаг 4: Запуск приложения
UITableViewDataSource
и UITableViewDelegate
.Шаг 1: Объявление протоколов и свойств
// ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@end
Шаг 2: Реализация в ViewController
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *fruits;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Инициализация данных
self.fruits = @[@"Яблоко", @"Банан", @"Апельсин", @"Киви", @"Манго"];
// Создание и настройка UITableView
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
// Установка делегатов
self.tableView.dataSource = self;
self.tableView.delegate = self;
// Регистрация класса ячейки
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
// Добавление UITableView на View
[self.view addSubview:self.tableView];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return self.fruits.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"
forIndexPath:indexPath];
cell.textLabel.text = self.fruits[indexPath.row];
return cell;
}
#pragma mark - UITableViewDelegate
// Здесь вы можете реализовать методы делегата, если нужно
@end
Шаг 3: Запуск приложения
Шаг 1: Добавление изображения в проект
Шаг 2: Создание UIImageView
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Устанавливаем цвет фона
self.view.backgroundColor = [UIColor whiteColor];
// Создаем UIImageView
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 300, 200)];
// Загружаем изображение
UIImage *image = [UIImage imageNamed:@"your_image_name"]; // Замените на имя вашего изображения
// Устанавливаем изображение в UIImageView
self.imageView.image = image;
// Настраиваем режим отображения
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
// Добавляем UIImageView на View
[self.view addSubview:self.imageView];
}
@end
Шаг 3: Запуск приложения
Шаг 1: Объявление UITextField и UILabel
// ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITextFieldDelegate>
@end
Шаг 2: Реализация в ViewController
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UILabel *displayLabel;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Создаем UILabel
self.displayLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 220, 40)];
self.displayLabel.text = @"Введите текст ниже:";
self.displayLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:self.displayLabel];
// Создаем UITextField
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 160, 220, 30)];
self.textField.borderStyle = UITextBorderStyleRoundedRect;
self.textField.delegate = self;
// Добавляем таргет для события изменения текста
[self.textField addTarget:self
action:@selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
[self.view addSubview:self.textField];
}
- (void)textFieldDidChange:(UITextField *)sender {
self.displayLabel.text = sender.text;
}
@end
Шаг 3: Запуск приложения
Шаг 1: Создание UIScrollView
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UIScrollView *scrollView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Создаем UIScrollView
self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
// Создаем содержимое, превышающее размер экрана
UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 1000)];
contentView.backgroundColor = [UIColor lightGrayColor];
// Добавляем элементы на contentView
for (int i = 0; i < 20; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, i * 50, self.view.bounds.size.width - 40, 40)];
label.text = [NSString stringWithFormat:@"Элемент %d", i+1];
[contentView addSubview:label];
}
// Добавляем contentView в scrollView
[self.scrollView addSubview:contentView];
// Устанавливаем размер содержимого scrollView
self.scrollView.contentSize = contentView.bounds.size;
// Добавляем scrollView на View
[self.view addSubview:self.scrollView];
}
@end
Шаг 2: Запуск приложения
Шаг 1: Создание UIAlertController и отображение его
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UIButton *alertButton;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Создаем кнопку для показа UIAlertController
self.alertButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.alertButton.frame = CGRectMake(100, 200, 200, 40);
[self.alertButton setTitle:@"Показать предупреждение" forState:UIControlStateNormal];
[self.alertButton addTarget:self
action:@selector(showAlertButtonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.alertButton];
}
- (void)showAlertButtonPressed {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Привет"
message:@"Это предупреждение"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"ОК"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
NSLog(@"Кнопка ОК нажата");
}];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
}
@end
Шаг 2: Запуск приложения
Шаг 1: Настройка AppDelegate с UINavigationController
// AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
// Создаем UINavigationController с корневым ViewController
ViewController *rootViewController = [[ViewController alloc] init];
UINavigationController *navigationController =
[[UINavigationController alloc] initWithRootViewController:rootViewController];
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
return YES;
}
@end
Шаг 2: Создание второго ViewController
// SecondViewController.h
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
@end
// SecondViewController.m
#import "SecondViewController.h"
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"Второй экран";
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 300, 40)];
label.text = @"Это второй экран";
[self.view addSubview:label];
}
@end
Шаг 3: Добавление кнопки для перехода и реализация перехода
// ViewController.m
#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UIButton *nextScreenButton;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Первый экран";
self.view.backgroundColor = [UIColor whiteColor];
self.nextScreenButton = [UIButton buttonWithType:UIButtonTypeSystem];
self.nextScreenButton.frame = CGRectMake(100, 200, 200, 40);
[self.nextScreenButton setTitle:@"Перейти на следующий экран" forState:UIControlStateNormal];
[self.nextScreenButton addTarget:self
action:@selector(nextScreenButtonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.nextScreenButton];
}
- (void)nextScreenButtonPressed {
SecondViewController *secondVC = [[SecondViewController alloc] init];
[self.navigationController pushViewController:secondVC animated:YES];
}
@end
Шаг 4: Запуск приложения
Шаг 1: Настройка AppDelegate с UITabBarController
// AppDelegate.m
#import "AppDelegate.h"
#import "FirstViewController.h"
#import "SecondViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
// Создаем контроллеры
FirstViewController *firstVC = [[FirstViewController alloc] init];
firstVC.title = @"Первая";
UINavigationController *firstNav = [[UINavigationController alloc] initWithRootViewController:firstVC];
SecondViewController *secondVC = [[SecondViewController alloc] init];
secondVC.title = @"Вторая";
UINavigationController *secondNav = [[UINavigationController alloc] initWithRootViewController:secondVC];
// Создаем UITabBarController
UITabBarController *tabBarController = [[UITabBarController alloc] init];
tabBarController.viewControllers = @[firstNav, secondNav];
self.window.rootViewController = tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
@end
Шаг 2: Создание FirstViewController и SecondViewController
// FirstViewController.h
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController
@end
// FirstViewController.m
#import "FirstViewController.h"
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"Первая вкладка";
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 300, 40)];
label.text = @"Это первая вкладка";
[self.view addSubview:label];
}
@end
// SecondViewController.h
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
@end
// SecondViewController.m
#import "SecondViewController.h"
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"Вторая вкладка";
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 300, 40)];
label.text = @"Это вторая вкладка";
[self.view addSubview:label];
}
@end
Шаг 3: Запуск приложения
Шаг 1: Импортирование WebKit
#import <WebKit/WebKit.h>
Шаг 2: Создание WKWebView
// ViewController.h
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
@interface ViewController : UIViewController
@end
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) WKWebView *webView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Создаем WKWebView
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
// Загрузка URL
NSURL *url = [NSURL URLWithString:@"https://www.apple.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
// Добавляем WKWebView на View
[self.view addSubview:self.webView];
}
@end
Шаг 3: Запуск приложения
Импортировать фреймворк
#import <CoreLocation/CoreLocation.h>
Настроить CLLocationManager
@interface ViewController () <CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager;
@end
Запрос разрешения и старт обновления местоположения
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
// Запрос разрешения (для iOS 8 и выше)
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
}
Реализовать методы делегата
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations {
CLLocation *location = [locations lastObject];
NSLog(@"Широта: %f, Долгота: %f", location.coordinate.latitude, location.coordinate.longitude);
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
NSLog(@"Ошибка получения местоположения: %@", error.localizedDescription);
}
Добавить описание в Info.plist
NSLocationWhenInUseUsageDescription
с описанием причины запроса местоположения.Шаг 1: Импортировать MapKit
#import <MapKit/MapKit.h>
Шаг 2: Объявить MKMapView
@interface ViewController ()
@property (nonatomic, strong) MKMapView *mapView;
@end
Шаг 3: Настроить MKMapView
- (void)viewDidLoad {
[super viewDidLoad];
// Создаем MKMapView
self.mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
// Устанавливаем делегата, если нужно
// self.mapView.delegate = self;
[self.view addSubview:self.mapView];
// Задаем регион отображения
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(55.7558, 37.6176); // Координаты Москвы
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coordinate, 10000, 10000);
[self.mapView setRegion:region animated:YES];
// Добавление аннотации
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = coordinate;
annotation.title = @"Москва";
[self.mapView addAnnotation:annotation];
}
Шаг 4: Настройка разрешений
Создание проекта с поддержкой Core Data
Модель данных
Настройка Core Data Stack в AppDelegate
persistentContainer
для доступа к NSManagedObjectContext
.Использование контекста
Сохранение объекта:
NSManagedObjectContext *context = self.persistentContainer.viewContext;
NSManagedObject *newEntity = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName"
inManagedObjectContext:context];
[newEntity setValue:@"Значение" forKey:@"атрибут"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Ошибка сохранения: %@", error.localizedDescription);
}
Запрос данных:
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"EntityName"];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(@"Ошибка запроса: %@", error.localizedDescription);
} else {
// Обработка результатов
}
Шаг 1: Импортировать AVFoundation
#import <AVFoundation/AVFoundation.h>
Шаг 2: Объявить AVAudioPlayer
@interface ViewController () <AVAudioPlayerDelegate>
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
@end
Шаг 3: Инициализация и воспроизведение
- (void)viewDidLoad {
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:@"audiofile" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:path];
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
self.audioPlayer.delegate = self;
if (error) {
NSLog(@"Ошибка инициализации плеера: %@", error.localizedDescription);
} else {
[self.audioPlayer prepareToPlay];
[self.audioPlayer play];
}
}
Шаг 4: Добавление аудиофайла в проект
Настройка в App Store Connect
Импортировать StoreKit
#import <StoreKit/StoreKit.h>
Реализация SKPaymentTransactionObserver
Запрос продуктов
@interface ViewController () <SKProductsRequestDelegate, SKPaymentTransactionObserver>
@end
- (void)viewDidLoad {
[super viewDidLoad];
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
[self fetchAvailableProducts];
}
- (void)fetchAvailableProducts {
NSSet *productIdentifiers = [NSSet setWithObject:@"product_id"];
SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers];
request.delegate = self;
[request start];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
SKProduct *product = response.products.firstObject;
SKPayment *payment = [SKPayment paymentWithProduct:product];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchased:
// Покупка успешна
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
// Покупка не удалась
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
default:
break;
}
}
}
- (void)dealloc {
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
Поздравляем! Вы познакомились с основными компонентами iOS SDK и научились работать с ними на практике. Мы рассмотрели, как создавать интерфейсы с помощью UIKit, работать с таблицами, отображать изображения, обрабатывать ввод пользователя, использовать прокрутку, показывать предупреждения, навигировать между экранами, управлять вкладками, отображать веб-контент, определять местоположение, работать с картами, управлять данными, воспроизводить аудио и реализовывать покупки внутри приложения.
Не забывайте практиковаться! Работа с компонентами iOS SDK открывает огромные возможности для создания функциональных и привлекательных приложений. Чем больше вы будете писать код и экспериментировать, тем лучше будете понимать, как создавать потрясающие приложения для iOS.
Удачи в ваших проектах!
Просмотров: 40