iOS心得7 按钮的图片和文字自定义位置
今天给大家看一下按钮的自定义效果
通常我们的需要效果如果有图有字的话,我们基本上都是使用uibutton这个控件。但是系统自带的效果是左图右字。如果你需要上图下字或者上字下图这种效果就需要自己去写。可能有的猿友没有做过这个。今天给大家一个实例。
Demo地址:https://github.com/sunyunfei/-Demo.git
首先我在故事板视图底部创建两个按钮,这一步操作就不说了,Demo里面很详细。
我自定义了两个按钮的类,让两个按钮分别继承他们。
第一个按钮我想要的效果是上图下字,这一步主要是通过两个方法实现的:
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;
一个是设置字的大小位置,一个是设置图的大小位置。
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat x = (contentRect.size.width \-(contentRect.size.height \-30))/2;
CGFloat y = -30;
return CGRectMake(x,y,contentRect.size.width,contentRect.size.height);
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat x = (contentRect.size.width \-(contentRect.size.height \-30))/2;
CGFloat y = 30;
return CGRectMake(x,y,contentRect.size.height \-30,contentRect.size.height \-30);
}
这是我写的简单的效果。当然你也可以在构造方法中写对图字一些舒心盖的设置:
- (id)initWithFrame:(CGRect)frame
{
self = \[super initWithFrame:frame\];
if (self) \{
//在构造的时候有作用
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
self.imageView.layer.cornerRadius = 15;
self.imageView.layer.masksToBounds = YES;
self.titleLabel.textAlignment = NSTextAlignmentCenter;
\}
returnself;
}
但是在我这个Demo里面是没有起作用,应该是我的按钮是画的没有经过构造函数造成的,有心的猿友可以试一下自己代码创建一个。
最后结果图:
≈
还没有评论,来说两句吧...