以足够的宽度显示UILabel的文本

时间:2019-01-08 07:04:43

标签: ios objective-c

按照 iOS编程:The Big Nerd Ranch Guide ,我尝试在Objective-c中使用Quiz项目。

此处的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

但是使用非可视文本运行当我点击按钮时,我已经连接了所有IBOutlet和动作。似乎有编译错误消息报告。

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

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

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

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