ios - 以足够的宽度显示 UILabel 的文本
问题描述
在iOS Programming: The Big Nerd Ranch Guide之后,我尝试使用 Objective-c 制作一个测验项目。
ViewController.m 代码在这里
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic) int currentQuestionIndex;
@property (nonatomic, copy) NSArray *questions;
@property (nonatomic, copy) NSArray *answers;
@property (nonatomic, weak) IBOutlet UILabel *questionLabel;
@property (nonatomic, weak) IBOutlet UILabel *answerLabel;
@end
@implementation ViewController
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
// Call the init method implemented by the superclass
self = [super initWithNibName:nil bundle:nil];
if (self) {
// create two arrays filled with questions and answers
// and make the pointers point to them
self.questions = @[@"From what is cognac made?",
@"What is 7+7?",
@"What is the capital of Vermont?"];
self.answers = @[@"Grapes",
@"14",
@"Montpelier"];
}
// Return the address of the new object
return self;
}
- (IBAction)showQuestion:(id)sender
{
// Step to the next question
self.currentQuestionIndex++;
// Am I past the last question?
if (self.currentQuestionIndex == [self.questions count]) {
// Go back to the first question
self.currentQuestionIndex = 0;
}
// Get the string at that index in the questions array
NSString *question = self.questions[self.currentQuestionIndex];
// Display the string in the question label
self.questionLabel.text = question;
// Reset the answer label
self.answerLabel.text = @"???";
}
- (IBAction)showAnswer:(id)sender
{
// What is the answer to the current question?
NSString *answer = self.answers[self.currentQuestionIndex];
// Display it in the answer label
self.answerLabel.text = answer;
}
@end
但是使用非可视文本运行当我点击按钮时,我已经连接了所有 IBOutlets 和操作。似乎已经编译错误消息报告。
解决方案
代码工作得很好,唯一的问题是数组没有初始化。您可以通过在结尾处放置一个断点initWithNibName:bundle:
并在开头放置一个断点来自行查看showQuestion:
:第一个断点永远不会被调用,当您点击“显示问题”按钮时,您会看到 apo self.questions
返回 nil。
如果您使用故事板(这是所有 Xcode 项目中的默认情况,因为有很多版本),您的视图控制器将永远不会调用initWithNibName:bundle:
,因为此方法旨在初始化基于 xib 的视图控制器。
您应该将该代码放入viewDidLoad
方法中,以便正确填充两个数组。
推荐阅读
- php - 在 slim 3 中找不到控制器
- python - 为什么 LogisticRegressionCV 的 .score() 与 cross_val_score 不同?
- java - java.sql.SQLSyntaxErrorException - 无法使用 JOINED 继承策略提取结果集
- flutter - 如何在 ListView Builder 中添加加号按钮从 Flutter 中的 SQLite 获取数据
- java - 在 gcp 控制台中运行 maven 命令时出错无法安装常见包错误
- vb.net - INSERT... ON DUPLICATE KEY UPDATE.... 这是错误 .System.NullReferenceException:Object reference not set to an instance of an object
- python - 为什么这些 python 片段相互矛盾?
- c++ - 如何将入口点过程从“WinMain”更改为“main”或任何自定义函数?
- javascript - 无法使用 JavaScript 播放音频
- ios - 通过按下它来更改 UICollectionView 单元格内的标签