利用示例:
class ViewController: UIViewController { private let listv: listView = { let view = listView() view.layer.cornerRadius = 10 view.layer.masksToBounds = true return view }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white listv.frame = CGRect(x: 15, y: 115, width: UIScreen.main.bounds.size.width-2*15, height: 5*listv.labelHeight) view.addSubview(listv) listv.arr = ["testA","testB","testC","testD","testE"] listv.addLabel() }}ListView代码:
private class listView: UIView { private var labela: [UILabel] = [] var arr: [String] = [] let labelHeight: CGFloat = 79 override init(frame: CGRect) { super.init(frame: frame) } required init?(coder: NSCoder) { fatalError("init(coder has not been implemented") } func addLabel() { for i in 0..<arr.count { let label = UILabel() label.frame = CGRect(x: 0, y: self.labelHeight*CGFloat(i), width: self.bounds.size.width, height: self.labelHeight) self.addSubview(label) label.tag = 100+i label.text = arr label.backgroundColor = .lightGray let tap = UITapGestureRecognizer.init(target: self, action: #selector(labelClick(tap)) label.isUserInteractionEnabled = true label.addGestureRecognizer(tap) let linev = UIView() linev.frame = CGRect(x: 0, y: label.bounds.size.height-1, width: label.bounds.size.width, height: 1) linev.backgroundColor = .systemGray label.addSubview(linev) labela.append(label) } } @objc private func labelClick(tap: UITapGestureRecognizer) { guard let label = tap.view as? UILabel else { return } for (index,item) in self.arr.enumerated() { if item == label.text { self.arr.remove(at: index) } } self.isUserInteractionEnabled = false updateLabel(label) } private func updateLabel(_ label: UILabel) { UIView.animate(withDuration: 1.5) { label.frame = CGRect(x: label.bounds.size.width, y: label.frame.origin.y, width: label.bounds.size.width, height: label.bounds.size.height) } completion: { suc in if suc { label.removeFromSuperview() for (index,item) in self.labela.enumerated() { if item.text == label.text { self.labela.remove(at: index) } } for i in 0..<self.labela.count { let temlabel = self.labela temlabel.frame = CGRect(x: 0, y: self.labelHeight*CGFloat(i), width: label.bounds.size.width, height: self.labelHeight) } self.frame = CGRect(x: self.frame.origin.x, y: 115, width: label.bounds.size.width, height: CGFloat(self.arr.count)*self.labelHeight) self.isUserInteractionEnabled = true } } } } |