[英]Can't programmatically change UILabel text after viewWillAppear
[英]can't change a UILabel text value inside a programmatically created custom view
因此,首先,我创建了一个自定义视图,其中包含一个UIImageView
和一个UILabel
。
.h文件:
#import <UIKit/UIKit.h>
@interface ImageText : UIView
@property (strong, nonatomic) IBOutlet ImageText *view;
@property (weak, nonatomic) IBOutlet UILabel *money;
@property (weak, nonatomic) IBOutlet UIImageView *image;
@end
这是.m文件
#import "ImageText.h"
@implementation ImageText
- (id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self = [[[NSBundle mainBundle] loadNibNamed:@"ImageText" owner:self options:nil] objectAtIndex:0];
}
return self;
}
@end
因此,有一个setLabelText
方法。 我在头文件中声明了它。 我希望能够创建此customview,然后更改UILabel
的文本。
在我的ViewController
的.m
我这样做:
ImageText *it = [[ImageText alloc] init];
[it.money setText:@"a"];
[_innercontent insertSubview: it belowSubview:_alishead];
[it setTranslatesAutoresizingMaskIntoConstraints:FALSE];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:it attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual toItem:nil
attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:59.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem: it attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual toItem:nil
attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:21.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_alishead attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual toItem:it
attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_alishead attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual toItem:it
attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]];
它使用以下代码创建View并将其放置在我想要的位置,但是setLabelText
方法什么也不做。 我尝试做类似的事情:
it.money.text = @"a";
这似乎也不起作用。 如何更改此文字?
我尝试删除设置器,尝试将其设置为强而不是弱,我尝试过[it.money setText:@“ a”]; 但没有一个有效。
检查.h文件中的IBOutlet是否正确链接到xib文件中的UILabel
我尝试做同样的事情,终于成功了。 下面是我的代码
if (self) {
self=[[[NSBundle mainBundle] loadNibNamed:@"YOUR_NIB_NAME" owner:self options:nil] objectAtIndex:0];
}
return self;
两种都可以使用init或initwithframe初始化
希望能帮助到你
从代码片段中可以清楚地看到,您在initWithFrame方法中定义了nib加载:但是您正在使用普通的alloc-init创建视图实例。 您必须使用[[ImageText alloc] initWithFrame:#someFrameOrZeroFrame]
创建它。 否则,您的笔尖将永远无法加载。
将视图添加到头文件时,应该选择视图而不是“ File's Owner
选项。 奇怪的是,在我观看的教程中,我应该选择文件的所有者。
我认为问题可能是对UILabel的错误引用,即Money。 给标签加上标签100,然后尝试通过viewwithtag将文本设置为标签。
UILabel * label =(UILabel *)[self.view viewWithTag:100]; label.text = @“您的文字”;
在您的情况下,self.view是ImageText的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.