我们经常会循环创建button,很多时候我们需要根据文字的长度来创建不同宽度的button。下面我们开始创建:
1.创建button:
func createButton() {
//dataSource是我的数据源
for i in 0..<dataSource!.count {
let button = UIButton(type: .Custom)
button.backgroundColor = YYMain_Color
button.layer.cornerRadius = 8.0
button.layer.masksToBounds = true
view.addSubview(button)
}
}
2.获取文字的长度:
//创建属性
let attributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.systemFontOfSize(14)]
//将String转换成NSString
let keyword: NSString = NSString(CString: dataSource![i].keyword!.cStringUsingEncoding(NSUTF8StringEncoding)!, encoding: NSUTF8StringEncoding)!
//获取文字的长度
let length = keyword.boundingRectWithSize(CGSizeMake(SCREEN_WIDTH, 2000), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil).size.width
3.把attribute给button:
//为button赋值
let attributeString = NSAttributedString(string: dataSource![i].keyword!, attributes: attributes)
button.setAttributedTitle(attributeString, forState: .Normal)
4.设置button的大小:
//先定义两个变量
var w: CGFloat = 0
var h: CGFloat = 90
//设置button的frame
button.frame = CGRectMake(10 + w, h, length + 15, 30)
//当button的位置超出右侧边缘时换行
if 10+w+length+15 > SCREEN_WIDTH {
w = 0
h = h + button.frame.size.height + 10
button.frame = CGRectMake(10+w, h, length+15, 30)
}
w = button.frame.size.width + button.frame.origin.x
OK👌效果如下:
循环创建button.png最终代码:
var w: CGFloat = 0
var h: CGFloat = 90
func createButton() {
for i in 0..<dataSource!.count {
let button = UIButton(type: .Custom)
button.backgroundColor = YYMain_Color
button.layer.cornerRadius = 8.0
button.layer.masksToBounds = true
let attributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont.systemFontOfSize(14)]
let keyword: NSString = NSString(CString: dataSource![i].keyword!.cStringUsingEncoding(NSUTF8StringEncoding)!, encoding: NSUTF8StringEncoding)!
let length = keyword.boundingRectWithSize(CGSizeMake(SCREEN_WIDTH, 2000), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil).size.width
//为button赋值
let attributeString = NSAttributedString(string: dataSource![i].keyword!, attributes: attributes)
button.setAttributedTitle(attributeString, forState: .Normal)
//设置button的frame
button.frame = CGRectMake(10 + w, h, length + 15, 30)
//当button的位置超出右侧边缘时换行
if 10+w+length+15 > SCREEN_WIDTH {
w = 0
h = h + button.frame.size.height + 10
button.frame = CGRectMake(10+w, h, length+15, 30)
}
w = button.frame.size.width + button.frame.origin.x
view.addSubview(button)
}
}
网友评论