IOS自定义View

来源:互联网 发布:抢魅族软件下载 编辑:程序博客网 时间:2024/06/13 05:00

1.自定义一个View作为一个小练笔

最终的效果如下


2.观察这个View有多少属性,第一个大的有UIImageView和一个UILableView,并且UILableView实在UIIamgeView下方浮着,这就需要定义他们的Frame并且两者的还有联系,下面的是整个头部

#import "IKEDViewController.h"#import "IKEDMyOwnImgView.h"@interface IKEDViewController ()@end@implementation IKEDViewController- (void)viewDidLoad{    [super viewDidLoad];    IKEDMyOwnImgView *imgview = [[IKEDMyOwnImgView alloc]initWithFrame:CGRectMake(2, 3, 200, 200)];        [imgview setImg:[UIImage imageNamed:@"1.jpg"]];        [imgview setTitle:@"hello world"];    [self.view addSubview:imgview];}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];}@end

3.主体实现

////  IKEDMyOwnImgView.m//  Ikefr////  Created by apple on 14-2-27.//  Copyright (c) 2014年 com.tyust. All rights reserved.//#import "IKEDMyOwnImgView.h"@implementation IKEDMyOwnImgView- (id)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {                _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];                _imageTitle = [[UILabel alloc]initWithFrame:CGRectZero];               _imageTitle.textAlignment = NSTextAlignmentCenter;                [self addSubview:_imageView];        [self addSubview:_imageTitle];    }    return self;}-(void)setImg:(UIImage *)img{    _imageView.image = img;        [self setTitleLableWidth:self.frame.size.width withHeight:self.frame.size.height/5];        [self setImgTitleColor:[UIColor blackColor] withBackGroundColor:[UIColor lightGrayColor]]; }-(void)setTitle:(NSString *)title{    _imageTitle.text = title;}-(void)setTitleLableWidth:(CGFloat)width withHeight:(CGFloat)height{    //lable的位置是和本身这个View的X相同,y是整个View高度的4/5    CGRect location = CGRectMake(0,_imageView.frame.size.height/5*4,width,height);    _imageTitle.frame = location;}-(void)setImgTitleColor:(UIColor*)textColor withBackGroundColor:(UIColor*)backgroundColor{    _imageTitle.textColor = textColor;    _imageTitle.backgroundColor = backgroundColor;}@end

3.外部应用

IKEDMyOwnImgView *imgview = [[IKEDMyOwnImgView alloc]initWithFrame:CGRectMake(2, 3, 200, 200)];        [imgview setImg:[UIImage imageNamed:@"1.jpg"]];        [imgview setTitle:@"hello world"];    [self.view addSubview:imgview];

5.注意问题

(1)在自定义的View里面一定要把里面要用的空间加入到这个View里面,否则不显示

(2)清楚明白各个控件的相对位置


6.大功告成



0 0