将uiimage附加到uiimage数组中



我希望下面的swift代码将每个表视图单元格中显示的所有图像附加到一个数组中。在这种情况下,数组为空A。我试着用DDBTn做这个动作。我在上遇到编译错误

let arrayValues2=collect.compactMap{UIImage($0.self.image(}

compactMap。我只想在调用func时将这些图像附加到数组中。

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

var emptyA = [UIImage]()
var addBTN = UIButton()
var tableView = UITableView()

override func viewDidLoad() {
super.viewDidLoad()

setTableVIew()
aDDBTn()


}


func setTableVIew(){


addBTN.backgroundColor = .orange
view.addSubview(addBTN)
addBTN.addTarget(self, action: #selector(aDDBTn), for: .touchDown)


let VCframe = view.frame
let height = VCframe.height * 0.8
let height2 = VCframe.height * 0.2
let widthx = VCframe.width
addBTN.frame = CGRect(x: 0, y: height, width: widthx, height: height2)

tableView.frame = CGRect(x: 10, y: 0, width: widthx - 20, height: height)

tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)


tableView.register(customtv.self, forCellReuseIdentifier: "cell")
}



var arr = [1,2,3,4]



func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 118 }


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! customtv


return cell
}
@objc func aDDBTn(){

let collect = (0..<arr.count).compactMap { (tableView.cellForRow(at: IndexPath(row: $0, section: 0)) as? customtv)?.lbl }
let arrayValues2 = collect.compactMap { UIImage($0.self.image) }
emptyA.append(contentsOf: arrayValues2)
print("Empty Array" , emptyA)
}


}
class customtv: UITableViewCell {
lazy var backView : UIView = {
let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width  , height: 110))
view.backgroundColor = .green
print(self.frame.width)
return view
}()



override func layoutSubviews() {
backView.clipsToBounds = true
backView.frame =  CGRect(x: 0, y: 6, width: bounds.maxX  , height: 110)


}
lazy var lbl : UIImageView = {
let press = UIImageView(frame: CGRect(x: 0, y: 3, width: 120 , height: 50))
press.backgroundColor = .yellow
press.image = UIImage(named: "a2")

return press
}()





override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(animated, animated: true)
addSubview(backView)

backView.addSubview(lbl)
}
}

由于lblUIImageView类型,因此collect的类型是基于以下行的[UIImageView]

let collect = (0..<arr.count).compactMap { (tableView.cellForRow(at: IndexPath(row: $0, section: 0)) as? customtv)?.lbl }

因此,您可以通过image属性直接访问图像。只需更改以下行

let arrayValues2 = collect.compactMap { UIImage($0.self.image) }

let arrayValues2 = collect.compactMap { $0.image }

最新更新