Home Backend Development PHP Tutorial Getting started with iOS 5 storyboards (4)

Getting started with iOS 5 storyboards (4)

Jan 20, 2017 am 10:26 AM

Let the AddPlayer window move

For now, let's ignore the "Game" line and only consider the player name entered by the user.
When the user touches the Cancel button, the window will be closed and all the data entered by the user will be lost. This part is OK. When the delegate object (Players window) receives the "didcancel" message, the AddPlayer window is simply closed.

When the user touches the done button, we should create a new Player object and set its properties. Then tell the delegate object that we have added a new player and he should refresh the interface.

Therefore, the done method in PlayerDetailsViewController.m becomes:

- (IBAction)done:(id)sender {
        Player *player = [[Player alloc] init];
        player.name = self.nameTextField.text;
        player.game = @"Chess";
        player.rating = 1;
        [self.delegate playerDetailsViewController:self         didAddPlayer:player];
}
Copy after login

We need to import the header file:

#import "Player.h"

The done method now creates a new Player object and sends it to the delegate object. The current delegation protocol in the PlayerDetailsViewController.h file needs to be modified to:

@class Player;  
@protocol PlayerDetailsViewControllerDelegate <NSObject>
- (void)playerDetailsViewControllerDidCancel:   (PlayerDetailsViewController *)controller;
- (void)playerDetailsViewController:   (PlayerDetailsViewController *)controller    didAddPlayer:(Player *)player;
@end
Copy after login

didSave method definition has been removed, and we have replaced it with a didAddPlayer method. The next period is to implement this method in

PlayersViewController.m:

  - (void)playerDetailsViewController:   (PlayerDetailsViewController *)controller    didAddPlayer:(Player *)player{
        [self.players addObject:player];
        NSIndexPath *indexPath =       [NSIndexPath indexPathForRow:[self.players count] - 1         inSection:0];
        [self.tableView insertRowsAtIndexPaths:       [NSArray arrayWithObject:indexPath]         withRowAnimation:UITableViewRowAnimationAutomatic];
        [self dismissViewControllerAnimated:YES completion:nil];
}
Copy after login

First add a new Player object to the players array. Then tell the table view to add the new row (at the bottom) because the table view and the data source must stay in sync. We could also use [self.tableView reloadData], but it would be better to animate the insertion of a new row. UITableViewRowAnimationAutomatic is a new constant that appeared in iOS 5. It will automatically select the appropriate animation depending on where you insert the row, which is very convenient.

Run the program and you should be able to add new players to the list!

You may suspect that there are performance issues with storyboards. But loading an entire storyboard at once is nothing fancy. The storyboard does not directly initialize all viewControllers, it only initializes the initial view controller. Because our initial view controller s is a TabBarController, the two view controllers it contains are also loaded (the Players View Controller and the second viewcontroller).

Other ViewControllers will not be initialized until you "segue" them. Once you close these ViewControllers, they are released, so only the currently used ViewController will stay in memory, just like the nib files you used.

Let's do an experiment. Add this method to PlayerDetailsViewController.m:

- (id)initWithCoder:(NSCoder *)aDecoder {
        if ((self = [super initWithCoder:aDecoder])) {
               NSLog(@"init PlayerDetailsViewController");
        }
        return self;
 }
- (void)dealloc {
        NSLog(@"dealloc PlayerDetailsViewController");
}
Copy after login

We override the initWithCoder and dealloc methods to output some information. Run the program again and open the Add Player window. You can see that the ViewController was not alloc'd until this point. Close the window (Cancel or Done button) and you can see the output of delloc. Open the window again and you can also see the content output by initWithCoder. This fully demonstrates that the Viewcontroller is loaded on demand, just like using the nib method.

One more thing, static cells can only be used in UITableViewController. The storyboard editor allows you to use static cells on a TableView in a regular UIViewController, but not at runtime. The reason is that UITableViewController provides a special data source mechanism for static cells. Xcode will even issue a warning to prohibit you from compiling such projects:

"Illegal Configuration: Statictable views are only valid when embedded in UITableViewController instances" (static table views are only valid for UITableViewController).

Template cell can be used in regular ViewController. Of course not in IB. Therefore, if you want to use template cells and static cells, you must use storyboards.

You may want to use static cells and dynamic cells in a table view at the same time, but the SDK does not support it. If you really want to do this, please refer here.

Note: If your window has too many static cells - more than the screen can accommodate - you can use mouse or trackpad scroll gestures to share the view in the storyboard editor. . This feature isn't very intuitive, but it's useful.

Game Picker Window

Tap the Game cell on the Add Player window and a list will open for the user to select a game. Therefore, a Table View Controller needs to be added. This time, we use the Push method instead of the Modal method.

Drag a new Table View Controller to the storyboard. Select the Game cell from the Add Player window (note that the entire cell is selected, not the Label above), hold down the ctrl key, and drag it to the new TableViewController. This will create a segue. Select the Push type segue and name the segue

as "PickGame".

Double-click the navigation bar and change the title to "Choose Game". The style of the template cell is set to Basic, and the reuse ID is set to "GameCell", as shown in the following figure:

Create a new UITableViewController subclass named GamePickerViewController. Don’t forget to set the Identifier of TableViewController in the storyboard to GamePickerViewController.

先让我们为新场景准备一些数据。在GamePickerViewController.h 中添加实例变量:

@interface GamePickerViewController : UITableViewController {
     NSArray * games;
}
Copy after login

在 GamePickerViewController.m 的viewDidLoad 方法中:

- (void)viewDidLoad {
        [super viewDidLoad];
        games = [NSArray arrayWithObjects:
              @"Angry Birds",
              @"Chess",
              @"Russian Roulette",
              @"Spin the Bottle",
              @"Texas Hold’em Poker",
              @"Tic-Tac-Toe",
              nil];
}
Copy after login

因为在 viewDidUnload 中初始化games 数组,所以必须在 viewDidUnload 中进行释放:

- (void)viewDidUnload {
        [super viewDidUnload];
        games = nil;
}
Copy after login

尽管这个窗口的 viewDidUnload实际上永远不会调用(我们永远也不会用另一个视图来覆盖它),但保持 release/alloc 平衡是一种良好的做法。

修改 TableView 的数据源方法:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return 1;
}
- (NSInteger)tableView:(UITableView *)tableView    numberOfRowsInSection:(NSInteger)section {
        return [games count];
}  
- (UITableViewCell *)tableView:(UITableView *)tableView    cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView       dequeueReusableCellWithIdentifier:@"GameCell"];
        cell.textLabel.text = [games objectAtIndex:indexPath.row];
        return cell;
}
Copy after login

关于数据源就这么多。运行程序,轻击 Game 行,Choose Game 窗口会出现。点击任何行都不会有任何动作。当然,由于窗口是以Push 方式呈现的,你可以点击导航栏的返回按钮返回 Add Player 窗口。

Getting started with iOS 5 storyboards (4)

这很好,不是吗?我们不需要写任何呈现新窗口的代码。只是从静态 cell 拖拽了一条线到新窗口而已。(注意当你点击Game 行是, table view 的委托方法即PlayerDetailsViewController的 didSelectRowAtIndexPath是会被调用的,请不要在其中加入任何代码,以免造成混乱)。

当然,目前新窗口还没有什么作用。 我们必须在 GamePickerViewController.h中定义一个新的委托协议使他能返回一些数据:

@class GamePickerViewController;  
@protocol GamePickerViewControllerDelegate <NSObject>
- (void)gamePickerViewController:   (GamePickerViewController *)controller    didSelectGame:(NSString*)game;
@end  
@interface GamePickerViewController : UITableViewController  
@property (nonatomic, weak) id <GamePickerViewControllerDelegate> delegate;
@property (nonatomic, strong) NSString *game;  
@end
Copy after login

修改 GamePickerViewController.m为:

@implementation GamePickerViewController {
        NSArray *games;
        NSUInteger selectedIndex;
}
@synthesize delegate;
@synthesize game;
Copy after login

添加了一个新的实例变量 selectedIndex,以及属性合成语句。

在 viewDidLoad 方法末增加:

selectedIndex = [games indexOfObject:self.game];
Copy after login


用户选定的游戏名称将保存到 self.game 中。selectedIndex则是 game 位于 games 数组中的索引。该索引用于在 TableView 中用一个对钩图标来标出所选 cell。因此,self.game 必须在视图加载之前就必须指定一个值。这可以通过prepareForSegue 方法进行,这个方法在 viewDidLoad 之前调用。

修改 cellForRowAtIndexPathto 方法为:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView       dequeueReusableCellWithIdentifier:@"GameCell"];
        cell.textLabel.text = [games objectAtIndex:indexPath.row];
        if (indexPath.row == selectedIndex)
               cell.accessoryType =            UITableViewCellAccessoryCheckmark;
        else
               cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;
}
Copy after login

在当前选定的游戏名称后面标志一个对钩图标。这对于用户来说应该是需要的。

修改 didSelectRowAtIndexPath方法如下:

- (void)tableView:(UITableView *)tableView    didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        if (selectedIndex != NSNotFound)      {
               UITableViewCell *cell = [tableView            cellForRowAtIndexPath:[NSIndexPath              
               indexPathForRow:selectedIndex inSection:0]];
               cell.accessoryType = UITableViewCellAccessoryNone;
        }
        selectedIndex = indexPath.row;
        UITableViewCell *cell =       [tableView cellForRowAtIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        NSString *theGame = [games objectAtIndex:indexPath.row];
        [self.delegate gamePickerViewController:self       didSelectGame:theGame];
}
Copy after login

首先反选改行。这将使单元格从高亮的蓝色变回正常的白色。然后移掉或添加单元格末尾的对钩标志(依赖于选中状态)。最终,将用于已选的游戏名称通过委托协议返回给委托对象。

运行程序进行测试。从游戏列表中点击一个游戏。该行末自动添加一个对钩。点击另一个游戏名称,对钩随之移动到新的选择。当你点击行时,窗口应该关闭,但什么也没发生。因为实际上我们还没有将委托对象连接进来。

#import "GamePickerViewController.h"

在 @interface 语句中添加协议:

@interface PlayerDetailsViewController : UITableViewController <GamePickerViewControllerDelegate>
   
在 PlayerDetailsViewController.m,添加prepareForSegue 方法:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        if ([segue.identifier isEqualToString:@"PickGame"]) {
               GamePickerViewController *gamePickerViewController =            segue.destinationViewController;
               gamePickerViewController.delegate = self;
               gamePickerViewController.game = game;
        }
}
Copy after login

就如我们前面所做的一样。这次的目标场景是 game picker 窗口。记住,该方法发生在GamePickerViewController 被初始化之后,视图被加载之前。

“game” 变量是新加的。它是一个实例变量:

@implementation PlayerDetailsViewController {
        NSString *game;
}
Copy after login

该变量用于存储用户选定的游戏,因此我们可以把它放到 Player 对象中。我们可以给它一个默认值。通过initWithCoder 方法是个不错的选择:

- (id)initWithCoder:(NSCoder *)aDecoder {
        if ((self = [super initWithCoder:aDecoder])) {
               NSLog(@"init PlayerDetailsViewController");
               game = @"Chess";
        }
        return self;
}
Copy after login

如果你用过 nib 文件,initWithCoder 你应该很熟悉。在故事板中,这些方法同样存在:initWithCoder、awakeFromNib和viewDidLoad。你可以把故事板看成是 nib 文件的集合,再加上它们之间的转换和关系。但是故事板中的 view controller 仍然是用同样的方法编码和解码。

修改 viewDidLoad ,让 Game 单元格显示游戏名:

- (void)viewDidLoad {
        [super viewDidLoad];
        self.detailLabel.text = game;
}
Copy after login

接下来实现委托方法:

#pragma mark - GamePickerViewControllerDelegate  
- (void)gamePickerViewController:   (GamePickerViewController *)controller    didSelectGame:(NSString*)theGame {
        game = theGame;
        self.detailLabel.text = game;
        [self.navigationController popViewControllerAnimated:YES];
}
Copy after login

很简单,将新游戏名称赋给我们的实例变量 game 以及 cell 的Label,然后关闭游戏选择窗口。由于它是一个 Push 式 segue,从导航控制器的栈顶中将它弹出即可。

在 done 方法中,我们将已选游戏放入 Player 对象:

- (IBAction)done:(id)sender {
        Player *player = [[Player alloc] init];
        player.name = self.nameTextField.text;
        player.game = game;
        player.rating = 1;
        [self.delegate playerDetailsViewController:self didAddPlayer:player];
}
Copy after login

好了,我们的游戏选择窗口就完成了!

接下来的内容

这是 示例工程源代码。

恭喜你,现在你已经基本掌握了故事板的使用,能够用 segue 在多个view controller 中导航及转换。

关于更多 iOS 5 中故事板的学习内容,请查看我们的新书iOS 5 教程,其中还包含了:

  • 修改 PlayerDetailsViewController 以便对 Player 对象进行编辑。

  • How to create multiple outgoing segues, how to make your ViewController reusable and handle multiple incoming segues.

  • How to call segue from disclosure button, gesture and any event.

  • Customize your segue - not just use the standard Push/Modal style animation!

  • How to use storyboards on iPad, including split-view controller and popover.

  • Finally, how to manually load storyboards and use multiple storyboards in the app.

The above is the content of iOS 5 storyboard introduction (4). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The first version of Apple's iOS 18 was exposed to have so many bugs: serious fever, WeChat delay The first version of Apple's iOS 18 was exposed to have so many bugs: serious fever, WeChat delay Jun 13, 2024 pm 09:39 PM

The annual WWDC has ended, and iOS18 is undoubtedly the focus of everyone's attention. Currently, many iPhone users are rushing to upgrade to iOS18, but various system bugs are making people uncomfortable. Some bloggers said that you should be cautious when upgrading to iOS18 because "there are so many bugs." The blogger said that if your iPhone is your main machine, it is recommended not to upgrade to iOS18 because the first version has many bugs. He also summarized several system bugs currently encountered: 1. Switching icon style is stuck, causing the icon not to be displayed. 2. Flashlight width animation is often lost. 3. Douyin App cannot upload videos. 4. WeChat message push is delayed by about 10 seconds. 5 . Occasionally, the phone cannot be made and the screen is black. 6. Severe fever.

Apple re-releases iOS/iPadOS 18 Beta 4 update, version number raised to 22A5316k Apple re-releases iOS/iPadOS 18 Beta 4 update, version number raised to 22A5316k Jul 27, 2024 am 11:06 AM

Thanks to netizens Ji Yinkesi, xxx_x, fried tomatoes, Terrence, and spicy chicken drumsticks for submitting clues! According to news on July 27, Apple today re-released the iOS/iPadOS 18 Beta 4 update for developers. The internal version number was upgraded from 22A5316j to 22A5316k. It is currently unclear the difference between the two Beta 4 version updates. Registered developers can open the "Settings" app, enter the "Software Update" section, click the "Beta Update" option, and then toggle the iOS18/iPadOS18 Developer Beta settings to select the beta version. Downloading and installing the beta version requires an Apple ID associated with a developer account. Reported on July 24, iO

Apple releases open source Swift package for homomorphic encryption, deployed in iOS 18 Apple releases open source Swift package for homomorphic encryption, deployed in iOS 18 Jul 31, 2024 pm 01:10 PM

According to news on July 31, Apple issued a press release yesterday (July 30), announcing the launch of a new open source Swift package (swift-homomorphic-encryption) for enabling homomorphic encryption in the Swift programming language. Note: Homomorphic Encryption (HE) refers to an encryption algorithm that satisfies the homomorphic operation properties of ciphertext. That is, after the data is homomorphically encrypted, specific calculations are performed on the ciphertext, and the obtained ciphertext calculation results are processed at the same time. The plaintext after state decryption is equivalent to directly performing the same calculation on the plaintext data, achieving the "invisibility" of the data. Homomorphic encryption technology can calculate encrypted data without leaking the underlying unencrypted data to the operation process.

Update | Hacker explains how to install Epic Games Store and Fortnite on iPad outside the EU Update | Hacker explains how to install Epic Games Store and Fortnite on iPad outside the EU Aug 18, 2024 am 06:34 AM

Update: Saunders Tech has uploaded a tutorial to his YouTube channel (video embedded below) explaining how to install Fortnite and the Epic Games Store on an iPad outside the EU. However, not only does the process require specific beta versions of iO

New features of Apple's iOS 18 'Boundless Notes” app: expanded Scenes functionality, introduced grid alignment New features of Apple's iOS 18 'Boundless Notes” app: expanded Scenes functionality, introduced grid alignment Jun 02, 2024 pm 05:05 PM

According to news on June 1, technology media AppleInsider published a blog post today, stating that Apple will launch a new navigation function of "Scenes" for the "Freeform" application extension in the iOS18 system, and add new options for object alignment. Introduction to the "Wubianji" application First, let's briefly introduce the "Wubianji" application. The application will be launched in 2022 and has currently launched iOS, iPadOS, macOS15 and visionOS versions. Apple’s official introduction is as follows: “Boundless Notes” is an excellent tool for turning inspiration into reality. Sketch projects, design mood boards, or start brainstorming on a flexible canvas that supports nearly any file type. With iCloud, all your boards

Apple iOS 17.5 RC version released: allows EU iPhone users to download apps from the website Apple iOS 17.5 RC version released: allows EU iPhone users to download apps from the website May 08, 2024 am 09:30 AM

[Click here to go directly to the upgrade tutorial] According to news on May 8, Apple pushed the iOS17.5RC update (internal version number: 21F79) to iPhone users today. This update is 70 days away from the last release. How to upgrade iOS/iPadOS/watchOS/macOS development version and public beta version? To upgrade the iOS/iPadOS17 developer preview version and public beta version, you can refer to the experience shared by friends: Experience Post 1||Experience Post 2||Experience Post 3||Experience Post 4. Starting from the iOS/iPadOS 16.4 Developer Preview Beta 1, you need to register for the Apple Developer Program. After registration, open the system [Settings] [Software Update] to see the upgrade option. Please note that your iPhone or IP

Apple iOS/iPadOS 18 Developer Preview Beta 4 released: Added CarPlay wallpapers, sorted out settings options, enhanced camera control Apple iOS/iPadOS 18 Developer Preview Beta 4 released: Added CarPlay wallpapers, sorted out settings options, enhanced camera control Jul 24, 2024 am 09:54 AM

Thanks to netizens Spicy Chicken Leg Burger, Soft Media New Friends 2092483, Handwritten Past, DingHao, Xiaoxing_14, Wowotou Eat Big Kou, Feiying Q, Soft Media New Friends 2168428, Slades, Aaron212, Happy Little Hedgehog, Little Earl, Clues for the little milk cat that eats fish! [Click here to go directly to the upgrade tutorial] According to news on July 24, Apple today pushed the iOS/iPadOS18 developer preview version Beta4 update (internal version number: 22A5316j) to iPhone and iPad users. This update is 15 days after the last release. . Carplay Wallpaper Apple has added wallpapers to CarPlay, covering light and dark modes. Its wallpaper style is similar to iPhone

Should iPhone12 ios16 be updated to ios17.5beta3? How is the experience of ios17.5beta3? Should iPhone12 ios16 be updated to ios17.5beta3? How is the experience of ios17.5beta3? Apr 25, 2024 pm 04:52 PM

Practical sharing... As Apple continues to launch new iOS versions, many iPhone users are faced with the choice of whether to upgrade the system. The release of the latest iOS17.5Beta3 has attracted widespread attention, especially for iPhone12 users. Whether they should abandon the existing iOS16 and try the new Beta version has become a question worth discussing. Based on actual experience, this article analyzes the pros and cons of upgrading iPhone 12 to iOS 17.5 Beta 3 to provide a reference for the majority of Apple fans. First of all, we need to make it clear that Beta versions are usually used by developers or early adopters who are willing to take a certain risk. This means that compared to the official version, the Beta version may contain

See all articles