我正嘗試創建一個使用標籤和手勢識別但基礎有點困難的基本項目。我創建了4個UILabel的界面,沿着應用屏幕的中心垂直放置。看起來是這樣的:使用標籤和手勢識別器不起作用的基本示例
問題
下一個問題
回答
顯示答案
...只是4個標籤,定位後的下一個。我從Interface Builder連接到我的ViewController.h
文件,爲每個標籤創建IBOutlet屬性。夠簡單。然後,我繼續寫下.m
文件中的所有實現代碼(見下文)。唯一的問題是當應用程序運行時,顯示的所有內容都是四個定位的標籤,其中包含來自Interface Builder的默認「標籤」文本。我添加到兩個標籤的手勢識別器似乎也沒有連接/觸發。
希望有人能爲我解決這個問題。開始是一個簡單的練習讓我有點生氣。
這是我的Viewcontroller.h文件:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic, strong) IBOutlet UILabel *labelQuestion;
@property (nonatomic, strong) IBOutlet UILabel *labelNextQuestion;
@property (nonatomic, strong) IBOutlet UILabel *labelAnswer;
@property (nonatomic, strong) IBOutlet UILabel *labelShowAnser;
@end
這是我的Viewcontroller.m文件:
#import "ViewController.h"
@interface ViewController()
@property (nonatomic, copy) NSArray *arrayQuestions;
@property (nonatomic, copy) NSArray *arrayAnswers;
@property (assign) int incrementer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// First create the datasource arrays with five elements each
self.arrayQuestions = [[NSArray alloc] init];
self.arrayQuestions = [NSArray arrayWithObjects:@"Who am I?", @"Who are you?", @"Where are we?", @"What's going on?", @"Why is this happening?", nil];
self.arrayAnswers = [[NSArray alloc] init];
self.arrayAnswers = [NSArray arrayWithObjects:@"Damian", @"Dmitri", @"I don't know.", @"You tell me.", @"I have no clue", nil];
// Reset the incrementer's value
self.incrementer = 0;
// Next configure the labels
self.labelQuestion = [[UILabel alloc] init];
self.labelQuestion.text = [self.arrayQuestions objectAtIndex:self.incrementer];
self.labelNextQuestion = [[UILabel alloc] init];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(nextQuestionLabelPressed)];
[tap setNumberOfTapsRequired:1];
[self.labelNextQuestion addGestureRecognizer:tap];
self.labelNextQuestion.text = @"Show next question";
self.labelAnswer = [[UILabel alloc] init];
self.labelAnswer.text = @"?????";
self.labelShowAnser = [[UILabel alloc] init];
self.labelShowAnser.userInteractionEnabled = YES;
UITapGestureRecognizer *tapp = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showAnswerLabelPressed)];
[tapp setNumberOfTapsRequired:1];
[self.labelShowAnser addGestureRecognizer:tapp];
self.labelShowAnser.text = @"Show answer";
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)nextQuestionLabelPressed {
self.incrementer++;
self.labelQuestion.text = [self.arrayQuestions objectAtIndex:self.incrementer];
self.labelAnswer.text = @"?????";
}
- (void)showAnswerLabelPressed {
self.labelAnswer.text = [self.arrayAnswers objectAtIndex:self.incrementer];
}
@end
嗯,我嘗試設置'userInteractionEnabled'爲兩個標籤的YES,但沒有任何區別。但是顯示的標籤不包含我將它們設置爲編程的文本。他們只是說「標籤」 – trigonoah
而我在下面的答案中解釋了爲什麼。 – matt