项目中需要设计一个星级评定的需求,特封装一个View作为星级评定的使用
效果如下:
自定义一个StarEvaluationView,在View上添加五个Button,点击对应的button将该button之前的按钮都设置为高亮图片,之后的按钮设置为默认图片
//
// LDStarEvaluationView.swift
//
//
import UIKit
//block回调
typealias LDStarEvaluationTapBlock = (_ starEvaluationView: LDStarEvaluationView,_ index : Int) ->()
class LDStarEvaluationView: UIView {
//block回调
var starEvaluationTapBlock: LDStarEvaluationTapBlock!
//默认图片
var defaultImage: UIImage?
//高亮图片
var lightImage: UIImage?
/// 星级评定
///
/// - Parameters:
/// - frame: 视图frame
/// - starIndex: 评定星级级别
/// - starWidth: 每个星星的宽度
/// - starSpace: 星星之间的间隔
/// - normalImage: 默认状态图片
/// - lightImage: 高亮状态图片
/// - isCanTap: 上方可以编辑
init(frame: CGRect, index starIndex: Int, width starWidth: CGFloat = 20, space starSpace: CGFloat = 5, normalImage defaultImage: UIImage = UIImage(named: "star_evaluation_normal")!,selectImage lightImage: UIImage = UIImage(named: "star_evaluation_light")!, isCanEdit isCanTap: Bool) {
super.init(frame: frame)
self.defaultImage = defaultImage
self.lightImage = lightImage
setupUI(index: starIndex, width: starWidth, space: starSpace, isTap: isCanTap)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI(index starIndex: Int, width starWidth: CGFloat, space starSpace: CGFloat, isTap isCanTap: Bool){
for i in 0..<5 {
let btn = UIButton()
btn.frame = CGRect(x: CGFloat(i) * (starWidth + starSpace), y: 0, width: starWidth, height: self.height)
btn.isEnabled = isCanTap
btn.tag = i + 1
btn.addTarget(self, action: #selector(starTapBtn(_:)), for: .touchUpInside)
btn.imageEdgeInsets = UIEdgeInsetsMake((self.height - starWidth) * 0.5, 0, (self.height - starWidth) * 0.5, 0)
if i < starIndex {
btn.setImage(self.lightImage, for: .normal)
} else {
btn.setImage(self.defaultImage, for: .normal)
}
btn.adjustsImageWhenHighlighted = false
self.addSubview(btn)
self.width = (starWidth + starSpace) * 5
}
}
@objc func starTapBtn(_ sender: UIButton) {
for i in 1...5 {
let starBtn = self.viewWithTag(i) as! UIButton
if i <= sender.tag {
starBtn.setImage(self.lightImage, for: .normal)
} else {
starBtn.setImage(self.defaultImage, for: .normal)
}
}
if starEvaluationTapBlock != nil {
starEvaluationTapBlock(self, sender.tag)
}
}
}
使用方法
let rect = CGRect(x: 100, y: textField.y + textField.height + 100, width: 150, height: 44)
let startView = LDStarEvaluationView(frame: rect, index: 3, isCanEdit: true)
startView.starEvaluationTapBlock = {(starView, starIndex) in
print(" \(starView ) \n \(starIndex)")
}
view.addSubview(startView)