如何使用子类函数将文本分配给MainClass中的UILabel?

时间:2012-11-10 14:11:13

标签: iphone xcode uitableview uilabel subclass

我在Mainclass中有一个UILabel,现在我想通过Subclass函数为它分配文本。我的问题详细代码可以在这里找到link现在我希望当我点击我的UITableview的任何Cell(我的子类)时,它的文本分配给Mainview中的UILabel。我的代码低于我为此尝试的

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
NSLog(@"MY row Text:%@",cellText);

// Now here I don't know how we can pass this text to UILabel which is in my mainclass

}

我的下图也有助于理解我的问题

enter image description here

2 个答案:

答案 0 :(得分:1)

将标签的引用传递给子类。然后子类可以简单地设置标签的文本。

在表视图控制器中添加属性UILabel * mainLabel。 然后将此属性设置为主类的标签引用。

答案 1 :(得分:1)

您可以在创建时将标签传递给子视图类。

在主视图中声明:

@property (nonatomic, strong) UILabel *mainLabel;
// or if no ARC
// @property (nonatomic, retain) UILabel *mainLabel;

然后在子视图的.h上,声明:

@property (nonatomic, weak) UILabel *myAccessToMainLabel;
// or if no ARC
// @property (nonatomic, assign) UILabel *myAccessToMainLabel;

创建子视图时,将主视图的Label分配给子视图的myAccessToMainLabel。然后在子视图代码中分配标签。您始终可以在Objective-c中传递属性。

编辑: 创建子视图时,从创建它的代码中将mainLabel分配给子视图的引用iVar。例如,如果main创建子视图,则:

MySubViewClass *mySubView = [[MySubViewClass alloc] initWithNib:@"MySubViewClass" ...];
// or any variety of init
mySubview.myAccessToMainLabel = mainLabel;