Swift 取数组的前8个放到另一个数组里

这篇博客介绍了如何在Swift中有效地从数组中取出前8个元素,并将其存储到新的数组中,讨论了Swift的数组操作技巧和性能考虑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//获取数据
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)
    
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值