![](/img/trans.png)
[英]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.