【发布时间】:2016-08-01 13:55:07
【问题描述】:
我想为坐标 UIView 创建全局变量,如何正确的语法来做到这一点?
【问题讨论】:
标签: ios objective-c global-variables
我想为坐标 UIView 创建全局变量,如何正确的语法来做到这一点?
【问题讨论】:
标签: ios objective-c global-variables
我建议不要使用两个浮点数,而是将坐标存储在专门为此制作的容器中:CGPoint。
要在全局范围内使用它,您可以将其添加到单例中(如@user3182143 答案),或在您的班级中公开它。
在您的.m 中,您可以将其定义为常量(在@interface 和@implementation 之外),如下所示:
const CGPoint kMyCoordinate = {.x = 100, .y = 200};
为了让其他类能够使用它,你需要在.h中暴露它,如下:
extern const CGPoint kMyCoordinate;
虽然在这种特殊情况下您通常使用CGPointMake(x,y) 创建CGPoints,但我们必须使用简写,否则Xcode 会抱怨“初始化器元素不是编译时常量”。
【讨论】:
.h中定义属性:@property (nonatomic) CGPoint myCoordinate;和.m中:self.myCoordinate = CGPointMake(100, 200);
首先你还需要创建 NSObject 类
给类名 GlobalShareClass
GlobalShareClass.h
#import <Foundation/Foundation.h>
@interface GlobalShareClass : NSObject
{
}
@property (nonatomic) float xvalue
@property (nonatomic) float yvalue
+ (GlobalShareClass *)sharedInstance;
@end
GlobalShareClas.m
#import "GlobalShareClass.h"
static GlobalShareClass *_shareInstane;
@implementation GlobalShareClass
@synthesize xvalue;
@synthesize yvalue;
+ (GlobalShareClass *)sharedInstance
{
if (_shareInstane == nil)
{
_shareInstane = [[GlobalShareClass alloc] init];
}
return _shareInstane;
}
ViewController.h
#import <UIKit/UIKit.h>
#import "GlobalShareClass.h"
@interface ViewController : UIViewController
{
GlobalShareClass *globalShare;
}
@end;
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
globalShare = [GlobalShareClass sharedInstance];
globalShare.xvalue = 50.0;
globalShare.xvalue = 100.0;
}
【讨论】:
在这里使用的正确的东西可能是类级别的属性。请参阅here 了解更多信息。
【讨论】: