在swift 3中删除表视图的特定选择单元格

时间:2017-08-09 13:46:25

标签: ios swift

我有一个表格视图和一个详细的View控制器,它与导航控制器一样连接,当我按下它时,它转到详细视图控制器,它在我的详细视图控制器中工作得很好I' m按下该按钮后,我想要一个按钮,我点击的特定单元格隐藏。我使用的是Swift 3 Xcode 8。

表格视图:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

    var delegate = SimpleProtocol.self

    @IBOutlet weak var tableview: UITableView!

    var cars = ["Ferrari", "Lamborghini", "Aston Martin", "Buggati", "Tesla"]
    var carslogo = ["images-7", "photo", "astonmartinlogo", "buggatilogo", "Tesla-Motors-logo-3"]


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    tableview.dataSource = self
    tableview.delegate = self
    tableview.contentInset = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: 0)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        tableview.reloadData()
    }

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

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let indexPath = tableView.indexPathForSelectedRow!

        self.performSegue(withIdentifier: "ss", sender: indexPath)
    }


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ss" {
            let details = segue.destination as! DetailViewController
            let indexPath = sender as! IndexPath
            details.view1 = cars[indexPath.row]
            details.view3 = UIImage(named: cars[indexPath.row])!

            if indexPath.row == 0 {
                details.view2 = ("Ferrari N.V. pronounced ferˈrari is an Italian sports car manufacturer based in Maranello. Founded by Enzo Ferrari in 1939 out of Alfa Romeo's race division as Auto Avio Costruzioni, the company built its first car in 1940. However the company's inception as an auto manufacturer is usually recognized in 1947, when the first Ferrari-badged car was completed.In 2014, Ferrari was rated the world's most powerful brand by Brand Finance. In May 2012 the 1962 Ferrari 250 GTO became the most expensive car in history, selling in a private transaction for US$38.1 million to American communications magnate Craig McCaw.Fiat S.p.A. acquired 50 percent of Ferrari in 1969 and expanded its stake to 90 percent in 1988.[5] In October 2014 Fiat Chrysler Automobiles announced its intentions to separate Ferrari S.p.A. from FCA; as of the announcement FCA owned 90 percent of Ferrari. The separation began in October 2015 with a restructuring that established Ferrari N.V. (a company incorporated in the Netherlands) as the new holding company of the Ferrari group and the subsequent sale by FCA of 10 percent of the shares in an IPO and concurrent listing of common shares on the New York Stock Exchange. Through the remaining steps of the separation, FCA's interest in Ferrari's business was distributed to shareholders of FCA, with 10 percent continuing to be owned by Piero Ferrari. The spin-off was completed on 3 January 2016.")   
            } else if indexPath.row == 1 {
                details.view2 = ("The Lamborghini Aventador is a mid-engined sports car produced by the Italian manufacturer Lamborghini.Launched on 28 February 2011 at the Geneva Motor Show, five months after its initial unveiling in Sant'Agata Bolognese, the vehicle, internally codenamed LB834, was designed to replace the then-decade-old Murciélago as the new flagship model.Soon after the Aventador unveiling, Lamborghini announced that it had already sold over 12 of the production vehicles, with deliveries starting in the second half of 2011. By March 2016, Lamborghini had already built 5,000 Aventadors, taking five years to achieve this milestone.")
            } else if indexPath.row == 2 {
                details.view2 = ("Aston Martin Lagonda Limited is a British manufacturer of luxury sports cars and grand tourers. It was founded in 1913 by Lionel Martin and Robert Bamford. Steered from 1947 by David Brown it became associated with expensive grand touring cars in the 1950s and 1960s, and with the fictional character James Bond following his use of a DB5 model in the 1964 film Goldfinger. Their sports cars are regarded as a British cultural icon. Aston Martin has held a Royal Warrant as purveyor of motorcars to HRH the Prince of Wales since 1982.Headquarters and the main production site are in Gaydon, Warwickshire, England, on the site of a former RAF V Bomber airbase. One of Aston Martin's recent cars was named after the 1950s Vulcan Bomber. Aston Martin has diversified to speed boats, and real estate development.")
            } else if indexPath.row == 3 {
                details.view2 = ("Automobiles Ettore Bugatti was a French car manufacturer of high-performance automobiles, founded in 1909 in the then German city of Molsheim, Alsace by Italian-born Ettore Bugatti. Bugatti cars were known for their design beauty (Ettore Bugatti was from a family of artists and considered himself to be both an artist and constructor[clarification needed]) and for their many race victories. Famous Bugattis include the Type 35 Grand Prix cars, the Type 41 Royale, the Type 57 Atlantic and the Type 55 sports car. The death of Ettore Bugatti in 1947 proved to be the end for the marque, and the death of his son Jean Bugatti in 1939 ensured there was not a successor to lead the factory. No more than about 8,000 cars were made. The company struggled financially, and released one last model in the 1950s, before eventually being purchased for its airplane parts business in the 1960s. In the 1990s, an Italian entrepreneur revived it as a builder of limited production exclusive sports cars. Today, the name is owned by German automobile manufacturing group Volkswagen.")
            }  else if indexPath.row == 4 {
                details.view2 = ("Tesla, Inc. (formerly named Tesla Motors) is an American automaker, energy storage company, and solar panel manufacturer based in Palo Alto, California.[7] The company was initially founded in 2003 by Martin Eberhard and Marc Tarpenning, although the company also considers Elon Musk, JB Straubel, and Ian Wright as its co-founders. The company specializes in electric cars, lithium-ion battery energy storage, and, through their SolarCity subsidiary, residential solar panels. Tesla first gained widespread attention following production of the Roadster, the first electric sports car, in February 2008. The companys second vehicle, the Model S, an electric luxury sedan, debuted in June 2012 and is built at the Tesla Factory in California. The Model S has been the world s best-selling plug-in electric car for two years in a row, 2015 and 2016. Its global sales achieved the 150,000 unit milestone in November 2016, four years and five months after its introduction. As of December 2016, the Model S ranks as the world's all-time second best-selling plug-in after the Nissan Leaf.")
            }
        }
    }

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

        let name = cars[indexPath.row]
        let logonmae = carslogo[indexPath.row]

        cell.label.text = name
        cell.logoimage.image = UIImage(named: logonmae)
        cell.image1.image = UIImage(named: name)

        return cell
    }  
}

详情视图控制器:

class Model: Object {
    dynamic var carname : String?
    dynamic var detail : String?
}

class DetailViewController: UIViewController {

    let object = ViewController()
    let ob = TableViewCell()

    var model : Model?
    let realm = try! Realm()

    @IBOutlet weak var detailimage: UIImageView!

    @IBOutlet weak var detaillabel: UILabel!

    @IBOutlet weak var detailtextfield: UITextView!

    @IBAction func button(_ sender: Any) {

        self.model = Model()

        model!.carname = self.detaillabel.text!
        model!.detail = self.detailtextfield.text!

        if let data = model {
            try! self.realm.write {
                self.realm.add(data)
            }
        }
    }

    var view1 = ""
    var view2 = String()
    var view3 = UIImage()

    override func viewDidLoad() {
        super.viewDidLoad()

        detaillabel.text = view1
        detailtextfield.text = view2
        detailimage.image = view3
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

1 个答案:

答案 0 :(得分:0)

根据我的推断,您在详细视图控制器上有一个按钮,并且在按下该按钮时,您要删除当前详细视图控制器所在的单元格。

您的方法应该是这样的:当您在detail view controller时,您应该通过您来自的单元格的index

现在,当用户点击该按钮时,您可以使用bool来检查或传递回您的表格视图。

当用户点击按钮并返回表格时,您实际应该传递索引和标记,然后在tableview类的viewwillappear中,您可以检查根据标志是否应删除所选索引,如果将index设置为删除,则只需使用索引从carscars-logo array中删除该项目,{ {1}}你的桌面视图。

这些可以改进很多,但这应该足够作为一个起点。