iOS程序-UIButton和UIImageView的区别

时间:2021-09-29 21:07:09

1.显示图片

 1> UIImageView只能一种图片(图片默认会填充整个UIImageView)  image\setImage:

 2> UIButton能显示2种图片

   * 背景 (背景会填充整个UIButton)  setBackroungImage:forState:

   * 前置(覆盖在背景上面的图片,按照之前的尺寸显示)  setImage:forState:

   * 还能显示文字

 

 2.点击事件

 1> UIImageView默认是不能响应点击事件(貌似可以添加事件http://blog.csdn.net/foolsong/article/details/25825531)

 2> UIButton能响应点击事件 : addTarget:action:forControlEvents:

 

 3.使用场合

 1> UIImageView : 只显示图片,不监听点击,点击了图片后不做任何反应

 2> UIButton : 既显示图片,又监听点击,点击了图片后做一些其他事情

 

 4.继承结构

 1> UIButton之所以能添加监听器来监听事件,是因为它继承自UIControl

 2> UIImagevIew之所以不能添加监听器来监听事件,是因为它直接继承自UIView

MJViewController.h

#import <UIKit/UIKit.h>
@interface MJViewController : UIViewController
@end

MJViewController.m

#import "MJViewController.h"
@interface MJViewController ()
@end
@implementation MJViewController
- (void)viewDidLoad
{
[super viewDidLoad];

// 1.添加ImageView
UIImageView *imageView = [[UIImageView alloc] init];
imageView.image = [UIImage imageNamed:@"014.png"];
imageView.frame = CGRectMake(0, 0, 150, 150);
[self.view addSubview:imageView];

// 2.UIButton
UIButton *btn = [[UIButton alloc] init];
// 设置背景图片
[btn setBackgroundImage:[UIImage imageNamed:@"bg.png"] forState:UIControlStateNormal];
// 设置前置图片
[btn setImage:[UIImage imageNamed:@"016.png"] forState:UIControlStateNormal];
btn.frame = CGRectMake(0, 100, 150, 150);

[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

[btn setTitle:@"我是按钮" forState:UIControlStateNormal];
[self.view addSubview:btn];

// UISlider *slider = [[UISlider alloc] init];
// slider.frame = CGRectMake(10, 250, 200, 50);
// slider.minimumValue = 10;
// slider.maximumValue = 20;
// [slider addTarget:self action:@selector(sliderChange:) forControlEvents:UIControlEventValueChanged];
// [self.view addSubview:slider];
}
- (void)sliderChange:(UISlider *)s
{
NSLog(@"%f", s.value);
}
- (void)btnClick:(UIButton *)mybtn
{
NSLog(@"%@", mybtn);
}
@end