//获取数据
func setLocalData() {
self.showHUD()
self.task = FetchManager.share.fetchBrandList(
success: { [unowned self] (list) -> (Void) in
DispatchQueue.main.async {
self.hidHUD()
//取返回的model对象list数组的前8个,放到brandButtonsArray数组里。如果返回的list少于8个,也不会有问题,有几个显示几个。写法就是下面这样,当然还有别的。
self.brandButtonsArray = [] + list.prefix(8)
//拿到数据去创建button
self.setBrandButtbons()
}
}, failure: { (error) in
DispatchQueue.main.async {
self.hidHUD()
self.showSystemAlert(error.errorDescription)
}
})
}
func setBrandButtbons() {
let itemSpace: CGFloat = 10.0
let width = (kScreenWidth - 5.0*itemSpace)/4.0
let height = width * 60 / 72
var lastButton: UIButton?
for (index, value) in self.brandButtonsArray.enumerated() {
let xIndex = index % 4
let yIndex = index / 4
let x = itemSpace + CGFloat(xIndex)*(width + itemSpace)
let y = 45 + CGFloat(yIndex)*(height + itemSpace)
let itemButton = UIButton(frame: CGRect(x: x, y: y, width: width, height: height))
itemButton.sd_setImage(with: URL(string: value.markPhotoPath!), for: .normal, placeholderImage: Utility.share.placeholderImage)
itemButton.layer.cornerRadius = 2
itemButton.layer.masksToBounds = true
itemButton.layer.borderWidth = 1
itemButton.layer.borderColor = CCGrayBorderColor.cgColor
itemButton.tag = index
itemButton.addTarget(self, action: #selector(itemButtonHandler(_:)), for: .touchUpInside)
self.brandView.addSubview(itemButton)
lastButton = itemButton
}
if let _ = lastButton {
self.brandViewHeight.constant = lastButton!.frame.maxY + itemSpace
self.view.updateConstraints()
}
}
@objc func itemButtonHandler(_ sender: UIButton) {
let brand = self.brandButtonsArray[sender.tag]
let viewController = CCProductListViewController(.brand(brand))
self.navigationController?.pushViewController(viewController, animated: true)
}