Objective-c iPhone 从另一个类读取并更改 UILabel 位置
我尝试更改 UILabel 的读取并更改位置。此 UILabel 已在 Interface Builder 中创建,现在当我调用 MainVieController 类中的方法时,我想读取并更改另一个类中的位置。
但我该如何做到这一点,我已经阅读了几个论坛,但我无法让它工作。这里还有一些示例代码。我希望有人能帮助我解决这个问题。
MainViewController.h
#import <UIKit/UIKit.h>
@class NewClass;
@interface MainViewController : UIViewController {
UILabel *daLabel;
}
@property (nonatomic, retain) IBOutlet UILabel *daLabel;
@end
MainViewController.m
#import "MainViewController.h"
#import "NewClass.h"
@implementation MainViewController
@synthesize daLabel;
- (void)viewDidLoad {
[super viewDidLoad];
NewClass *anotherClass = [[NewClass alloc] init];
[anotherClass test];
}
@end
NewClass.h
#import <Foundation/Foundation.h>
@class MainViewController;
@interface NewClass : NSObject {
}
@end
NewClass.m
#import "NewClass.h"
#import "MainViewController.h"
@implementation NewClass
- (void)test {
MainViewController *MainController = [[MainViewController alloc] init];
CGRect labelPosition = MainController.daLabel.frame;
NSLog(@"POSITION: %f", labelPosition.origin.x); // Returns 0.000000
}
@end
I try to change the read and change the position from a UILabel. This UILabel has been created in Interface Builder and now i want to read and change the position inside another class, when i call a method in the MainVieController class.
But how can i do that, i've read several forums but i can't get it work. Here's also some sample code. I hope someone can help me with this.
MainViewController.h
#import <UIKit/UIKit.h>
@class NewClass;
@interface MainViewController : UIViewController {
UILabel *daLabel;
}
@property (nonatomic, retain) IBOutlet UILabel *daLabel;
@end
MainViewController.m
#import "MainViewController.h"
#import "NewClass.h"
@implementation MainViewController
@synthesize daLabel;
- (void)viewDidLoad {
[super viewDidLoad];
NewClass *anotherClass = [[NewClass alloc] init];
[anotherClass test];
}
@end
NewClass.h
#import <Foundation/Foundation.h>
@class MainViewController;
@interface NewClass : NSObject {
}
@end
NewClass.m
#import "NewClass.h"
#import "MainViewController.h"
@implementation NewClass
- (void)test {
MainViewController *MainController = [[MainViewController alloc] init];
CGRect labelPosition = MainController.daLabel.frame;
NSLog(@"POSITION: %f", labelPosition.origin.x); // Returns 0.000000
}
@end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定为什么您要在 NewClass 中创建视图控制器的另一个实例,该实例由视图控制器加载。也许只是在调用测试方法时传递“self”?但如果你想改变 UILabel 的位置,只需改变 labelPosition ,然后将 daLabel.frame 设置为修改后的 labelPosition 即可。例如:
I'm not sure why you're creating another instance of your view controller in NewClass, which is loaded by your view controller. Maybe just pass "self" in the call to the test method? But if you want to change the position of your UILabel, just change labelPosition and then set daLabel.frame to the modified labelPosition. For example: