如何将数组发送到子视图然后打印到标签?

时间:2012-05-03 05:32:08

标签: objective-c xcode storyboard subview

在故事板上工作。

我已经创建了View Controller(storyboard),然后在内容中添加了来自xib文件的子视图。

我想将xib(UIView)作为子视图添加到ViewController中,并使用数据发送对象并将该数据打印到标签中,但我不知道如何。

这是我的代码。

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController {
    UIView *subView;
}

@property (strong, nonatomic) IBOutlet UIView *subView; //connected over IB
@end

ViewController.m

#import "OfferViewController.h"
#import "OfferLocation.h"

@interface OfferViewController ()

@end

@implementation OfferViewController

@synthesize subView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    OfferLocation *location = [[OfferLocation alloc] initWithFrame:CGRectZero];
    [self.subView addSubview:location];
}
...
@end

这是子视图: 的 OfferLocation.h

#import <UIKit/UIKit.h>

@interface OfferLocation : UIView{
    UIView *view;
    UILabel *locationLabel;// here is that label taht I want to print into
}

@property (nonatomic, retain) IBOutlet UIView *view;// connected over IB
@property (nonatomic, retain) IBOutlet UILabel *locationLabel;

@end

OfferLocation.m

#import "OfferLocation.h"

@implementation OfferLocation

@synthesize view, locationLabel;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        locationLabel.text = @"some text"; //this is not working
        NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"OfferLocation" owner:self options:nil];
        UIView *tempView = [subviewArray objectAtIndex:0];
        [self addSubview:tempView];
    }
    return self;
}

1 个答案:

答案 0 :(得分:0)

subView似乎从未被初始化并加载到视图或呈现。因此你看不到它。

尝试致电:

            self.view = self.subView // or subView; // or [self.view addSubview:self.subView // or subview];

或类似的东西

然后声明一个UILabel并用你想要的任何文本初始化它并将其添加到子视图中:

         UILabel *label = [[UILabel alloc] initWithString:@"StackOverflow rocks!"];
         [self.subView addSubview:label];
// or [self.view addSubview:label];

不同于您如何设置子视图。

您要在标签文字上设置的数据是什么?如果是数据类型,请使用字符串中的说明符。

        %i // for int
%@ // for string or object adress
%c // for char
%f // for float

等...