6-2 项目 老师我在设置金钱那里,没有显示出这个view
来源:6-2 作业题
SiuNam
2018-10-11 15:13:57
//
// ViewController.m
// 看图猜字游戏
//
// Created by on 2018/10/9.
// Copyright © 2018年 lzn. All rights reserved.
//
#import "ViewController.h"
#import "DiyCoinView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self addUpView];
[self addcoinView];
}
-(void)addUpView{
UIView *UpView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 375, 390)];
UpView.backgroundColor = [UIColor colorWithRed:178/255.0 green:34/255.0 blue:34/255.0 alpha:1];
[self.view addSubview:UpView];
}
//硬币图片加个数
-(void)addcoinView{
DiyCoinView *coinView = [[DiyCoinView alloc]initWithFrame:CGRectMake(244, 20, 131, 30)];
coinView.backgroundColor = UIColor.clearColor;
[self.view addSubview:coinView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end//
// DiyCoinView.m
// 看图猜字游戏
//
// Created by 刘兆南 on 2018/10/10.
// Copyright © 2018年 lzn. All rights reserved.
//
#import "DiyCoinView.h"
#import "ViewController.h"
@implementation DiyCoinView
-(id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
//图片
UIImageView* coinView =[[UIImageView alloc]init];
[coinView setImage:[UIImage imageNamed:@"coin.png"]];
coinView.frame=CGRectMake(244 ,20 , coinView.image.size.width, coinView.image.size.height);
//钱
UILabel* money = [[UILabel alloc]initWithFrame:CGRectMake(244+coinView.image.size.width, 20+coinView.image.size.height, 70, 30)];
money.text = @"20000";//初始金钱
money.textColor = [UIColor whiteColor];//白色字体
/*money.font = [UIFont systemFontOfSize:17];//默认使用系统的17
money.shadowColor = [UIColor lightGrayColor];//默认没有阴影
money.shadowOffset = CGSizeMake(1,0);//默认是一个向上的阴影(0,-1)
money.textAlignment = NSTextAlignmentCenter;//默认是左对齐
money.lineBreakMode = NSLineBreakByTruncatingTail;//段落样式,默认是最后截断尾巴,用...代替
*/
[self addSubview:coinView];
[self addSubview:money];
}
return self;
}
@end
1回答
Tender10
2018-10-11
下面是自定义UIView的一个步骤哦。
1、新建一个继承UIView的类,比如起名叫MyButton
2、在刚刚新建类的类扩展中添加子控件属性,一个是显示图片的控件,一个是显示文字的控件
@property (nonatomic, weak) UIImageView *iconImageView; @property (nonatomic, weak) UILabel *nameLabel;
3、在initWithFrame:方法中添加子控件
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
UIImageView *iconImageView = [[UIImageView alloc] init];
self.iconImageView = iconImageView;
[self addSubview:iconImageView];
UILabel *nameLabel = [[UILabel alloc] init];
nameLabel.textAlignment = NSTextAlignmentCenter;
nameLabel.font = [UIFont systemFontOfSize:10];
self.nameLabel = nameLabel;
[self addSubview:nameLabel];
}
return self;
}4、在layoutSubviews方法中设置子控件的frame(在该方法中一定要调用[super layoutSubviews]方法)在这个方法里,去设置iconImageView、nameLabel两个控件的位置,x,y,width,height
- (void)layoutSubviews{}5、后面想在同一个view中又显示图片有显示文字,就可以直接导入MyButton类,然后初始化这个类,然后赋值相关的值,然后添加到self.view上就可以啦。