-2

変数の境界、幅、高さは現在ローカル変数です。他のクラスからアクセスすることも、別のメソッドからアクセスすることもできません。

これらの変数をインスタンス全体で使用できるようにするにはどうすればよいですか?それらを.hファイル内に配置し、名前をCGFloatsに変更してみましたが無駄になりました。

#import "TicTacToeBoard.h"

@implementation TicTacToeBoard

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    CGRect bounds = [self bounds];
    float width = bounds.size.width;
    float height = bounds.size.height;

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(ctx, 0.3, 0.3, 0.3, 1);
    CGContextSetLineWidth(ctx, 5);
    CGContextSetLineCap(ctx, kCGLineCapRound);

    CGContextMoveToPoint(ctx, width/3, height * 0.95);
    CGContextAddLineToPoint(ctx, width/3, height * 0.05);
    CGContextStrokePath(ctx);

}

@end
4

4 に答える 4

1

境界、幅、高さは、drawRectメソッドのコンテキストにのみ存在するローカル変数です。

使ってみませんか:

CGRect bounds = [self bounds];
float width = bounds.size.width;
float height = bounds.size.height;

他の方法で?

于 2011-11-07T16:58:36.870 に答える
1

プロパティを使用して、変数を他のオブジェクトにアクセスできるようにすることができます。

インターフェイスに次のようなものを追加します。

@property (nonatomic, retain) NSString *myString;

次に追加します

@synthesize mystring;

あなたの実装に。

プロパティを取得して変更するために、2つのメソッドが作成されます。

[myObject myString]; // returns the property
[myObject setMyString:@"new string"]; // changes the property

// alternately, you can write it this way
myObject.myString;
myObject.mystring = @"new string";

を使用してクラス内のプロパティの値を変更できます。[self setMystring:@"new value"]または、インターフェイスで同じ変数がすでに宣言されている場合は、そこからプロパティを作成して、クラス内の変数を現在のように使用し続けることができます。

開発者向けドキュメントには、プロパティに関する詳細情報があります:http: //developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17 -SW1

于 2011-11-07T17:04:57.023 に答える
0

それらをメンバー変数またはプロパティにし、アクセサーを作成するか、それらを合成します。 Objective-C言語リファレンスを参照してください

于 2011-11-07T16:57:50.023 に答える
0

ゲッターセッターを使用するか、

@property(nonatomic) CGFloat width;

@synthesize width;
于 2011-11-07T16:58:15.203 に答える