最近马上放假所以比较忙,今天简单写一个项目中出现的单选按钮的横竖样式,PS:封装的是Swift语言样式
首先创建一个UIView的类,然后创建方法,最后调用类中的方法进行显示
//参数一:需要显示的内容数据,参数二:类型:1、横;2、竖
func hSingleSelBtn(titleArray:NSArray, typeE aTypeE:Int) {
let frameE:CGRect = self.frame;
let aWidthH:CGFloat = frameE.width;
let aHeightT:CGFloat = frameE.height;
if aTypeE==1 {
//横向
let widthH:CGFloat = (aWidthH-20-30*CGFloat(titleArray.count))/CGFloat(titleArray.count);
for i:Int in 0 ..< titleArray.count {
let btn = UIButton.init(frame: CGRectMake(10+(widthH+20)*CGFloat(i), (aHeightT-16)/2, 16, 16));
btn.setImage(UIImage.init(named: "unchoose"), forState: .Normal);
btn.setImage(UIImage.init(named: "choose"), forState: .Selected);
if i==0 {
btn.selected = true;
}else{
btn.selected = false;
}
btn.tag = i+10000;
btn.addTarget(self, action: #selector(btnClick), forControlEvents: .TouchUpInside);
self.addSubview(btn);
let labelL = UILabel.init(frame: CGRectMake(40+(widthH+20)*CGFloat(i), 0, widthH, aHeightT));
labelL.text = titleArray[i] as? String;
labelL.adjustsFontSizeToFitWidth = true;
self.addSubview(labelL);
}
}else{
//纵向
let hidthH = CGFloat(aHeightT / CGFloat(titleArray.count));
for i:Int in 0 ..< titleArray.count {
let btn = UIButton.init(frame: CGRectMake(10, (hidthH-16)/2 + hidthH * CGFloat(i), 16, 16));
btn.setImage(UIImage.init(named: "unchoose"), forState: .Normal);
btn.setImage(UIImage.init(named: "choose"), forState: .Selected);
if i==0 {
btn.selected = true;
}else{
btn.selected = false;
}
btn.tag = i+10000;
btn.addTarget(self, action: #selector(btnClick), forControlEvents: .TouchUpInside);
self.addSubview(btn);
let labelL = UILabel.init(frame: CGRectMake(40, hidthH * CGFloat(i), aWidthH, hidthH));
labelL.text = titleArray[i] as? String;
labelL.adjustsFontSizeToFitWidth = true;
self.addSubview(labelL);
}
}
currentTag = 10000;
}
func btnClick(btn:UIButton) {
if !btn.selected {
btn.selected = !btn.selected;
//上一个按钮还原
let buttonN = self.viewWithTag(currentTag) as? UIButton;
buttonN?.selected = false;
currentTag = btn.tag;
}
}
视图的展示使用
//横向数量少的单选,两三个
let titleArr:NSArray = ["男","女"];
let sexLabel = UILabel.init(frame: CGRectMake(10, 100, 50, 40));
sexLabel.text = "性别";
self.view.addSubview(sexLabel);
let bgView = SingleSelBtnView.init(frame: CGRectMake(60, 100, 200, 40));
//bgView.backgroundColor = UIColor.lightGrayColor();
bgView.hSingleSelBtn(titleArr, typeE: 1);
self.view.addSubview(bgView);
//纵向数量可多个
let titleArr1:NSArray = ["A.北京","B.上海","C.广州","D.深圳"];
let oneLabel = UILabel.init(frame: CGRectMake(10, 200, 100, 40));
oneLabel.text = "单选题";
self.view.addSubview(oneLabel);
let bgView1 = SingleSelBtnView.init(frame: CGRectMake(60, 250, 200, 200));
//bgView1.backgroundColor = UIColor.lightGrayColor();
bgView1.hSingleSelBtn(titleArr1, typeE: 2);
self.view.addSubview(bgView1);
效果展示:
源码Demo(还有定义屏幕宽高的方法):http://download.csdn.net/detail/hbblzjy/9643958