[英]UiLabel text assignment in custom view
我在其他自定義視圖(容器)內創建了一個自定義視圖(自定義視圖)。 然后在主視圖中,將自定義視圖添加為子視圖。 在那之后,我試圖通過屬性設置文本,它不起作用。
#import <UIKit/UIKit.h>
@interface Bage : UIView
@property (nonatomic,strong) UILabel *title;
@end
#import "Bage.h"
@implementation Bage
@synthesize title;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:CGRectMake(0, 0, 45, 25)];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
//// General Declarations
CGContextRef context = UIGraphicsGetCurrentContext();
//// Shadow Declarations
UIColor* shadow = UIColor.blackColor;
CGSize shadowOffset = CGSizeMake(3.1, 3.1);
CGFloat shadowBlurRadius = 3;
//// Variable Declarations
CGFloat buttonWidth = rect.size.width - 2 - 4;
CGFloat buttonHeigh = rect.size.height - 2 - 4;
//// Frames
// CGRect frame = CGRectMake(frSize.origin.x, frSize.origin.y, frSize.size.width, frSize.size.height);
//// Rectangle Drawing
UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(1, 1, buttonWidth, buttonHeigh) cornerRadius: 8];
CGContextSaveGState(context);
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, [shadow CGColor]);
[UIColor.whiteColor setFill];
[rectanglePath fill];
CGContextRestoreGState(context);
[[UIColor greenColor] setStroke];
rectanglePath.lineWidth = 1;
[rectanglePath stroke];
title = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(rect) + 1, CGRectGetMinY(rect) + 1, CGRectGetWidth(rect) - 6, CGRectGetHeight(rect) - 6)];
title.textColor = [UIColor blackColor];
title.textAlignment = NSTextAlignmentCenter;
[self addSubview:title];
}
@end
#import <UIKit/UIKit.h>
#import "Bage.h"
@interface CustomView : UIView
@property (nonatomic,strong) Bage *myBage;
@end
#import "CustomView.h"
@implementation CustomView
@synthesize myBage;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
myBage = [[Bage alloc] init];
self.backgroundColor = [UIColor greenColor];
myBage.title.text = @"Class text";
myBage.center = self.center;
[self addSubview:myBage];
}
return self;
}
@end
#import "ViewController.h"
#import "CustomView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor blueColor];
CustomView *cView = [[CustomView alloc] initWithFrame:CGRectMake(30, 30, 200, 200)];
[self.view addSubview:cView];
cView.myBage.backgroundColor = [UIColor clearColor];
cView.myBage.title.text = @"Text";
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
請幫助我在我的行李中輸入文字。
不要在drawRect:中將標題添加為子視圖。 初始化Bage視圖時,應執行此操作。 另外,您使用的是drawRect:中賦予的rect,它並不總是視圖的邊界。 因此,在您的初始值設定項中添加標題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.