3

私はObjective Cの初心者で、オブジェクトの操作方法がわかりません。UILabel を作成し、テキストとその他すべてを設定できます。しかし、別のメソッドから更新したいと思います..つまり、テキストを変更したいのですが、そのメソッドにオブジェクトがありません!

それがUILabelの設定方法です

- (void)viewDidLoad
{
    [super viewDidLoad];
    UILabel *scoreLabel = [ [UILabel alloc ] initWithFrame:CGRectMake((self.view.bounds.size.width / 2), 0.0, 150.0, 43.0) ];
    scoreLabel.textAlignment =  UITextAlignmentCenter;
    scoreLabel.textColor = [UIColor whiteColor];
    scoreLabel.backgroundColor = [UIColor redColor];
    scoreLabel.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:(36.0)];
    [self.view addSubview:scoreLabel];
    scoreLabel.text = [NSString stringWithFormat: @"%d", 0];
}

UILabel のテキストを変更したいところです

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.crossView.alpha = 0.5;
    ...change scoreLabel.test 
}

どちらのメソッドも ViewController にあります!

UILabel を自分自身にバインドできますか? しかし、どのように?

4

5 に答える 5

11

.h で UILabel のプロパティを作成する必要があるため、ViewController を考慮して変更できます。

あなたの.hでこれを前に追加してください@end

@property (strong, nonatomic) UILabel *scoreLabel;

あなたのviewDidLoadよりも代わりにこれを行います:

- (void)viewDidLoad
{
    [super viewDidLoad];
    _scoreLabel = [ [UILabel alloc ] initWithFrame:CGRectMake((self.view.bounds.size.width / 2), 0.0, 150.0, 43.0) ];
    _scoreLabel.textAlignment =  UITextAlignmentCenter;
    _scoreLabel.textColor = [UIColor whiteColor];
    _scoreLabel.backgroundColor = [UIColor redColor];
    _scoreLabel.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:(36.0)];
    [self.view addSubview:_scoreLabel];
    _scoreLabel.text = [NSString stringWithFormat: @"%d", 0];
}

後でビューコントローラーで:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.crossView.alpha = 0.5;
    _scoreLabel.text = @"CHANGED TEXT";
}
于 2013-01-14T16:14:20.607 に答える
2

クラス プロパティを定義するための追加オプションとして、インスタンスのtagプロパティを設定しUILabel、後でラベルのコンテンツを更新するときに、次を使用してこのラベルを取得できます。

UILabel *label = (UILabel *)[self.view viewWithTag:someTag];

このメソッドは、現在のビューとそのすべてのサブビューで、指定されたビューを検索します。

于 2013-01-14T16:42:37.590 に答える
1

ヘッダーで:

@property(nonatomic, retain) UILabel *scoreLabel;

および .m (メソッドの外側、通常は行の直後@implementation [ClassName];):

@synthesize scoreLabel;

次に、インスタンス化するときは、次のようにします。

self.scoreLabel = [[UILabel alloc ] initWithFrame:CGRectMake((self.view.bounds.size.width / 2), 0.0, 150.0, 43.0)];

self.scoreLabel.m のどこでも参照できます。

于 2013-01-14T16:13:25.933 に答える
1

あなたのインターフェースでこれを書いてください

interface YourViewController{
    ....
    UILabel *scoreLabel
}
.....

@end

実装では、この方法で変数に簡単にアクセスできます

@Implementation YourViewController
....
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.crossView.alpha = 0.5;
    scoreLabel.text = @"Your Text"
}
....
@end
于 2013-01-14T16:16:49.693 に答える
0

UILabel でテキスト/文字列を設定するには、次を使用します。

self.yourLabel.text=@"Your String";
于 2016-06-13T13:31:30.063 に答える