我希望下面的快速代码将显示在每个tableview单元格中的所有图像附加到数组中。在这种情况下,数组是emptyA。我试着在aDDBTn中做这个动作。我收到了一个编译错误
设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)
}
}发布于 2020-08-27 02:00:42
collect的类型是基于以下行的[UIImageView],因为lbl是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 }https://stackoverflow.com/questions/63606582
复制相似问题