首页 > 解决方案 > 以足够的宽度显示 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 和操作。似乎已经编译错误消息报告。

在此处输入图像描述 在此处输入图像描述

标签: iosobjective-c

解决方案


代码工作得很好,唯一的问题是数组没有初始化。您可以通过在结尾处放置一个断点initWithNibName:bundle:并在开头放置一个断点来自行查看showQuestion::第一个断点永远不会被调用,当您点击“显示问题”按钮时,您会看到 apo self.questions返回 nil。

如果您使用故事板(这是所有 Xcode 项目中的默认情况,因为有很多版本),您的视图控制器将永远不会调用initWithNibName:bundle:,因为此方法旨在初始化基于 xib 的视图控制器。

您应该将该代码放入viewDidLoad方法中,以便正确填充两个数组。


推荐阅读