如何在uiview中刷新uilabel文本

时间:2018-03-19 14:56:03

标签: ios objective-c uiview uiscrollview uibutton

有一个名为HiView的UIView的子类

HiView.h

#import <UIKit/UIKit.h>
@interface HiView : UIView
@property (nonatomic, retain) UILabel *textcontent;
@end

HiView.m

@implementation HiView
@synthesize textcontent;
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
    textcontent = [[UILabel alloc] init];
    [self addSubview:textcontent];
}
return self;
}

- (void)layoutSubviews {
    //some codes
}
@end

在UIViewController中,有一个UIScrollView

@interface TheVC ()
@property (nonatomic, retain) HiView *hiview;
@end
//some codes
UIScrollView *scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.view addSubview:scrollview];
for (int index=0; index<5; index++) {
    _hiview = [[HiView alloc] init];
    _hiview.frame = CGRectMake(self.view.frame.size.width * index, 50, self.view.frame.size.width, self.view.frame.size.height);
    [scrollview addSubview:_hiview];
}

并且在这个UIViewController中有一个按钮,当我点击它时,hiview中的UILabel应该改变,现在我使用_hiview.textcontent.text = "changed";,但它似乎不起作用,任何想法?

2 个答案:

答案 0 :(得分:0)

你应该创建一个数组来保存所有的hiviews并在任何地方进行更改,因为你当前的实现仅引用了最后一个视图,你创建的实例变量视图不能保存对所有视图的引用,因为它是单个对象,这是

@property (nonatomic, retain) HiView *hiview;

//所以创建一个数组

@interface ViewController ()
{
    NSMutableArray*allViews
}

//将每个新创建的hiview添加到其中

for (int index=0; index<5; index++) {
    HiView*hiview = [[HiView alloc] init];
    hiview.frame = CGRectMake(self.view.frame.size.width * index, 50, self.view.frame.size.width, self.view.frame.size.height);
    [scrollview addSubview:hiview];
    [allViews addObject:hiview];
}

答案 1 :(得分:0)

使用标记来保存对您的观看次数的参考 并从.h

中删除hiview属性
String

然后你会说

UUID