如何解决将uiimages附加到uiimage数组
我希望我下面的快速代码将每个tableview单元格中显示的所有图像附加到数组中。在这种情况下,数组为空。我试图在ADDBTn中执行此操作。我在上出现编译错误
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,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)
}
}
解决方法
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 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。