这种方法创建的简单明了对位置的改动容易,点击后的高亮状态可以参考,获取uiimage纯色图片,然后调用- (void)setImage:(UIImage *)image forState:(UIControlState)state;就可以改动点击后颜色(背景颜色),效果还是不错的
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 1, 0, 0, 1 });
[self.layer setMasksToBounds:YES];
[self.layer setCornerRadius:10.0]; //设置矩形四个圆角半径
[self.layer setBorderWidth:1]; //边框宽度
[self.layer setBorderColor:colorref];//边框颜色
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.frame.size.height/2-image.size.height/6), image.size.width/3, image.size.height/3)];
imageView.image = image;
imageView.userInteractionEnabled = YES;
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(image.size.width/3+20, self.frame.size.height/2-20, self.frame.size.width-image.size.width/3-20, 40)];
titleLabel.textColor = [UIColor whiteColor];
titleLabel.font = [UIFont fontWithName: @"Helvetica-Bold" size : 17.0 ];
titleLabel.text = title;
[self addSubview:titleLabel];
[self addSubview:imageView];
}
(非原创)UIButton上的图片和文字位置调整:
属性: imageEdgeInsets
contentEdgeInsets
UIEdgeInsetsMake
Creates an edge inset for a button or view.
UIEdgeInsets UIEdgeInsetsMake (
CGFloat top, //距离上方
CGFloat left, //距离左边
CGFloat bottom, 、//距离下方
CGFloat right //距离右方
);
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];//button的类型
button.frame = CGRectMake(100, 100,90, 90);//button的frame
button.backgroundColor = [UIColor cyanColor];//button的背景颜色
// 在UIButton中有三个对EdgeInsets的设置:ContentEdgeInsets、titleEdgeInsets、imageEdgeInsets
[button setImage:[UIImage imageNamed:@"IconHome@2x.png"] forState:UIControlStateNormal];//给button添加image
button.imageEdgeInsets = UIEdgeInsetsMake(5,13,21,button.titleLabel.bounds.size.width);//设置image在button上的位置(上top,左left,下bottom,右right)这里可以写负值,对上写-5,那么image就象上移动5个像素
[button setTitle:@"首页" forState:UIControlStateNormal];//设置button的title
button.titleEdgeInsets = UIEdgeInsetsMake(71, -button.titleLabel.bounds.size.width-50, 0, 0);//设置title在button上的位置(上top,左left,下bottom,右right)
// button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
(非原创)重写UIButton的//重写父类UIButton的方法
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- - (CGRect)imageRectForContentRect:(CGRect)contentRect;
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat titleW = contentRect.size.width-30;
CGFloat titleH = contentRect.size.height;
CGFloat titleX = 0;
CGFloat titleY = 0;
contentRect = (CGRect){{titleX,titleY},{titleW,titleH}};
return contentRect;
}
//更具button的rect设定并返回UIImageView的rect
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imageW = 25;
CGFloat imageH = 25;
CGFloat imageX = contentRect.size.width-26;
CGFloat imageY = 2.5;
contentRect = (CGRect){{imageX,imageY},{imageW,imageH}};
return contentRect;
}