【问题标题】:Global variable in Objective-C in ios proj [closed]ios proj中Objective-C中的全局变量[关闭]
【发布时间】:2016-08-01 13:55:07
【问题描述】:

我想为坐标 UIView 创建全局变量,如何正确的语法来做到这一点?

【问题讨论】:

    标签: ios objective-c global-variables


    【解决方案1】:

    我建议不要使用两个浮点数,而是将坐标存储在专门为此制作的容器中:CGPoint

    要在全局范围内使用它,您可以将其添加到单例中(如@user3182143 答案),或在您的班级中公开它。

    在您的.m 中,您可以将其定义为常量(在@interface@implementation 之外),如下所示:

    const CGPoint kMyCoordinate = {.x = 100, .y = 200};

    为了让其他类能够使用它,你需要在.h中暴露它,如下:

    extern const CGPoint kMyCoordinate;

    虽然在这种特殊情况下您通常使用CGPointMake(x,y) 创建CGPoints,但我们必须使用简写,否则Xcode 会抱怨“初始化器元素不是编译时常量”。

    【讨论】:

    • 我认为你的回答是最方便的。我想过使用 CGPoint 。
    • 在我的“.h”中添加 @property(nonatomic, assign) CGPoint* lastScrollOffset;并且在我的“.m”中我必须打电话给他并分配给我的当前位置我的视图我的猫是怎么做到的?
    • 如果要使用属性而不是类常量,那么在.h中定义属性:@property (nonatomic) CGPoint myCoordinate;.m中:self.myCoordinate = CGPointMake(100, 200);
    • 我在逻辑上是不可能的。从顶部有 VIEV 大小取决于内容,它可能会改变它的高度。在它进入 tableView 之后,哪个 NSLayoutConstraint 到 topLayout 视图取决于上面的大小。而且我需要在滚动 contentOffset.y 期间捕捉它发生了多少变化并将其传输到我的全局变量中,该变量将以其初始坐标为 sravnimat
    【解决方案2】:

    首先你还需要创建 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;
    
    } 
    

    【讨论】:

      【解决方案3】:

      在这里使用的正确的东西可能是类级别的属性。请参阅here 了解更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-07
        • 2017-04-30
        • 1970-01-01
        相关资源
        最近更新 更多