【发布时间】:2015-12-10 12:21:40
【问题描述】:
这是我实现自定义 UiView 的方式
在 myView.h 文件中
@interface myView : UIView
{
NSString *message;
}
...
@property (nonatomic, retain) UILabel *messageLabel;
...
@end
在 myView.m 文件中
此函数将实例化 myView 并为其添加消息标签
+ (id) initWithText:(NSString *) text
{
screenBounds = [[UIScreen mainScreen] bounds];
CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
self = [super initWithFrame:CGRectMake(0, statusBarFrame.size.height, screenBounds.size.width, 40)];
if (self)
{
[self setBackgroundColor:[UIColor redColor]];
message = [text copy];
_messageLabel = [[UILabel alloc]initWithFrame:[self frame]];
[_messageLabel setText:message];
[_messageLabel setAdjustsFontSizeToFitWidth:YES];
[_messageLabel setTextAlignment:NSTextAlignmentJustified];
[_messageLabel setTextColor:[ UIColor blackColor]];
[self addSubview:_messageLabel];
}
return self;
}
稍后我将 myView 作为子类添加到屏幕中的可见视图中。当我运行应用程序时,我可以看到红色的 myView,但其中没有显示消息标签。
【问题讨论】:
-
很可能标签的位置或大小不正确。
-
你在哪里调用 initWithText?
-
尝试在 UILabel 初始化中将 [self frame] 更改为 [self bounds]。
-
@SuryaSubenthiran 我试过
[self bounds]即使这样它也没有显示标签。只有红色背景的 UiView 可见 -
@beyowulf 我从另一个文件调用 initWithText。我使用
[[[myView alloc]initWithText:@"My Message"] show];调用它。 show 函数会将视图添加到窗口中,因为我可以在屏幕中看到 myView 但其中没有显示 UiLabel。
标签: ios objective-c iphone uiview uilabel