swift 第四课 随意 设置button 图片和文字 位置

项目中经常遇到按钮改变文字和图片位置的情况,所以尝试写一个 button 的分类:

参照连接 http://blog.csdn.net/dfqin/article/details/37813591

import Foundation
import UIKit

/*
枚举 设置 图片的位置
*/
enum ButtonImagePosition : Int{ case PositionTop =
case Positionleft
case PositionBottom
case PositionRight
} extension UIButton {
/**
imageName:图片的名字
title:button 的名字
type :image 的位置
Space :图片文字之间的间距
*/
func setImageAndTitle(imageName:String,title:String,type:ButtonImagePosition,Space space:CGFloat) { self.setTitle(title, for: .normal)
self.setImage(UIImage(named:imageName), for: .normal) let imageWith :CGFloat = (self.imageView?.frame.size.width)!;
let imageHeight :CGFloat = (self.imageView?.frame.size.height)!; var labelWidth :CGFloat = 0.0;
var labelHeight :CGFloat = 0.0; labelWidth = CGFloat(self.titleLabel!.intrinsicContentSize.width);
labelHeight = CGFloat(self.titleLabel!.intrinsicContentSize.height);
var imageEdgeInsets :UIEdgeInsets = UIEdgeInsets();
var labelEdgeInsets :UIEdgeInsets = UIEdgeInsets(); switch type {
case .PositionTop:
imageEdgeInsets = UIEdgeInsetsMake(-labelHeight - space/2.0, , , -labelWidth);
labelEdgeInsets = UIEdgeInsetsMake(, -imageWith, -imageHeight-space/2.0, );
break;
case .Positionleft:
imageEdgeInsets = UIEdgeInsetsMake(, -space/2.0, , space/2.0);
labelEdgeInsets = UIEdgeInsetsMake(, space/2.0, , -space/2.0);
break;
case .PositionBottom:
imageEdgeInsets = UIEdgeInsetsMake(, , -labelHeight-space/2.0, -labelWidth);
labelEdgeInsets = UIEdgeInsetsMake(-imageHeight-space/2.0, -imageWith, , );
break;
case .PositionRight:
imageEdgeInsets = UIEdgeInsetsMake(, labelWidth+space/2.0, , -labelWidth-space/2.0);
labelEdgeInsets = UIEdgeInsetsMake(, -imageWith-space/2.0, , imageWith+space/2.0);
break;
} // 4. 赋值
self.titleEdgeInsets = labelEdgeInsets;
self.imageEdgeInsets = imageEdgeInsets;
}
}

调用方法:

/*
使用方便 用xib 中建立的 leftBtn
*/
 
leftBtn.setImageAndTitle(imageName: "hezuojigou", title: "合作机构", type: .PositionTop, Space: 0.0)
上一篇:移动App崩溃测试用例设计


下一篇:cocos2d 场景转换的方法执行顺序