2017-09-23 11 views
0

私が今直面している主な問題は、detailPathへの移行中にindexPath.rowが各セクションのリセットを続けていることです。この問題を解決するのを手伝ってください。セクションを含むdetailViewにtableViewからデータを渡すにはどうすればよいですか?

望ましい結果は次のようになりますように

Birds 
Olive-backed sunbird 
Black naked oriole 

Plants 
Bamboo orchid 
- 
- 

...

TableViewController.swift

class RainforestTableViewController: UITableViewController { 

    var names:NSArray = [[]] 
    var scientificNames:NSArray = [] 
    var descriptions:NSArray = [] 

    lazy var rainforestCategory: [Rainforest] = { 
     return Rainforest.rainforestCategories() 
    }() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.tableView.separatorColor = UIColor.clear 

     names = ["OLIVE-BACKED SUNBIRD", "BLACK-NAPED ORIOLE", "COMMON MYNAH", "JAVAN MYNAH", "ORIENTAL WHITE EYE", "SCARLET-BACKED FLOWERPECKER", "GOLDEN BELLIED GERYGONE", "BAMBOO ORCHIRD", "BIRD'S NEST FERN", "BLUE PEA VINE", "CREPE GINGER", "ELEPHANT EAR PLANT", "PINK MEMPAT", "SCARLET MILKWEED", "TORCH GINGER","CARPENTER BEE", "COMMON GREEN BOTTLE FLY", "FLESH FLY", "HOVERFLY", "LACEWING", "OLEANDER APHIDS", "YELLOW SPOTTED MILLIPEDE", "AUTUMN LEAF BUTTERFLY", "CHOCOLATE PANSY", "COMMON GRASS YELLOW", "FRUIT PIERCING MOTH", "LIME BUTTERFLY", "PEACOCK PANSY", "PLAIN TIGER BUTTERFLY", "SHORT BANDED SAILOR", "YELLOW PALM DART BUTTERFLY", "HÜBNER'S WASP MOTH", "GARDEN LIZARD", "TABBY CAT", "PLANTAIN SQUIRREL", "FRUIT BAT"] 

     scientificNames = ["Cinnyris jugularis", "Oriolus chinensis", "Acridotheres tristis", "Acridotheres javanicus", "Zosterops palpebrosus", "Dicaeum cruentatum", "Gerygone sulphurea", "Arundina graminifolia", "Asplenium nidus", "Clitoria ternatea", "Cheilocostus speciosus", "t Colocasia esculenta", "Cratoxylum formosum", "Asclepias curassavica", "Etlingera elatior", "Xylocopa", "Lucilia sericata", "Sarcophagidae", "Syrphidae", "Chrysopidae", "Aphis nerii", "Harpaphe haydeniana", "Doleschallia bisaltide", "Junonia iphita", "Eurema hecabe", "Eudocima phalonia", "Papilio demoleus", "Junonia almana", "Danaus chrysippus", "Neptis columella", "Cephrenes trichopepla", "Amata huebneri", "Calotes versicolor", "TABBY CAT", "Callosciurus notatus", "Megachiroptera"] 

     descriptions = ["The Olive-Backed Sunbird drinks the sweet nectar inside the flowers. Most species can take nectar by hovering, but usually perch to feed most of the time. Nectar is a poor sauce of nutrients, so they meet their needs for protein, amino acids, vitamins and minerals by preying on insects and spiders. Both the male and the female assist in building the nest which is flask-shaped, with an overhanging porch at the entrance. Both male and female assist in the care of the young, which leave the nest about 2 or 3 weeks later.", "It has a distinctive black and yellow plumage, and a pinkish bill. This species of bird inhabits gardens, parks, and spend most of their time in the canopy level. They are most active in the morning and evening, and you can frequently hear the clear and melodious whistle.", "This bird is readily identified by their brown body and bright yellow bill and legs. They are usually seen in pairs. The Common Mynah is omnivorous, feeding on insects like grasshoppers and caterpillars, reptiles, grains and fruits and discarded food waste by humans.", "This bird is readily identified by their brown body and bright yellow bill and legs. They are usually seen in pairs. The Common Mynah is omnivorous, feeding on insects like grasshoppers and caterpillars, reptiles, grains and fruits and discarded food waste by humans.", "The Oriental White Eye is a small but fast-moving bird. This bird typically has a cycle of feathers around the eye. The head, wings and tail are usually olive in colour. The Oriental White Eye usually feeds on berries and small insects. Being a small bird, its predators include bats and other birds such as Kingfishers. This species of bird, also known as mata puteh, is often kept as pets because of its ability to sing well", "Scarlet-Backed Flowerpecker is a common garden bird, identified by a streak of red from the crown to tail. ", "Golden Bellied Gerygone is a hard bird to spot as it makes a fairy-like call by turning its head all around while making the sound and it is often described as rather week notes that carry an amazing distance", "The Bamboo Orchird consists of white, pink and purple colour, blooming one at a tine at the tip of the cane. The flowers are attractive to bees and butteflies. The plants have slender, grasslike leaves and grow up to 3 metres tall. Bamboo Orchird grows in sunny, open, disturbed areas in our Rainforest", "The Bird's Nest Fern is a large leafy fern commonly found on rain trees and along walkways. The nest traps water together with fallen leaves and other debris which eventually decomposes into humus. Spores can be found on the underside of the leaf.", "Blue Pea Vine is a plant that is native to Asia. It grows as a vine or creeper, with its distinctive deep blue petals with light yellow markings. The fruits are about 5 to 7 cm long, flat pods with 6 to 10 seeds in each pod. They are edible when tender. In Southeast Asia, the flowers are used to colour food. In Malay cooking, an aqueous extract is used to colour glutinous rice for kueh ketan", "Crepe Ginger differs form the common ginger by having only one row of spirally arranged leaves. The pure white crinkled flower emerges from a red cone-shaped bract, attracting pollinatos like the Carpenter Bee. The texture of its flower resembles the crepe papaer. Crepe Ginger is native to Singapore.", "Elephant Ear Plant is reminiscent of the ears of an elephant. The huge leaf surface provides a good shade. The plant sap contains an irritant which causes intense discomfort and the acridity helps to naturally deter herbivores from eating it.", "The Pink Mempat is commonly known as the Sakura of Singapore due to its mass flowering. Our local climate of uniformly wet without prolonged period of dry spell does not encourage mass flowering. However, the prolonged dry spell in the recent months as well as the sudden heavy rains has triggered the intense mass flowering. This tree was first planted in our school during the 50th Anniversary Homecoming by then Senior Parliamentary Secretary for Ministry of Manpower and Ministry of Education, Mr Hawazi Daipi on 14th May 2014.", "Scarlet Milkweed has showy red and yellow flowers. It is grown as an ornamental garden plant, a food source for butterflies and it's sap is milky. Flowering occurs all year round and every time after the fruit is formed, it splits open and the flat brown seeds will be dispersed with the help of the silky hairs that allow the seeds to float on air currents", "The Torch Ginger is a herb that has a waxy-petalled flower, resembling a torch. Due to the wax in the petals, the flower is not very aromatic. However, when cut, the flower bud releases an aromatic flavour with citrus notes and a hint of pepper. The ginger can be shredded and used in salads and sauces. It is an indispensable ingredient in Nonya dishes such as Asam Laksa. It can also be found in Rojak, together with fruit and dough fritters.", "Carpenter Bees are large, sturdy, shiny and black coloured. Some specied have yellow markings on the head. Carpenter Bees can be important pollinators on open-faced flowers. Males bees are often seen hovering near nests, and will approach nearby animals. In fact, male bees are actually harmless as they do not have a stinger. Female bees are capable of stinging, but they are docile and rarely sting unless caught in the hand or otherwise provoked. They often cause fear in many people due to their large size, intimidating appearance and loud buzzing. However, it is safe to watch this gentle giant collecting nectar and pollen.", "The Common Green Bottle Fly has a brilliant metallic green colouration with black markings. Its back is hairy and it is usually 8 to 10mm long. It prefers warm and moist climate.", "The Flesh Fly feeds on decaying matter", "The Hoverfly is often seen hovering or nectaring at flowers. Its larvae feeds on decaying plant and animal matter in the soil and also prey on aphids and other plant-sucking insects. Those plant-sucking insects can cause tens of millions of dollars worth of damage to crops worldwide every year. Therefore, Hoverflies are being recognised as important natural enemies of pests. Despite their mimicry of more dangerous wasps and bees to ward off predators, hoverflies are harmless to most other animals. In fact, they are excellent biological control against the Oleander Aphids whcih have been infesting the Scarlet Milkweed plants.", "The Lacewing is an insect which naturally controls many pests. Although the adult Lacewing does not kill other insects but survives on sweet nectar, its larvae which has the appearance of an alligator with pincers like tiny ice tongs, attacking its prey by injecting a paralyzing venom and then drawing out the fluids of its victim. It has a verocious appetite for aphids. ", "Oleander Aphids is a common pest for ornamental plants in the milkweed family. The females adults are often mistaken as yellow pollen grains. They suck the plant sap from the ends of the milkweed plant and stunt the plant growth. Each aphids ingests sap from the phloem of its host plant, then exrete drops of sticky honeydew which the ants feed on. Natural biological controls of the aphids include the Lacewing and Ladybug. However, the ants might also help to defend the Oleander Aphids from being attacked by these natural predators.", "YELLOW SPOTTED MILLIPEDE", "AUTUMN LEAF BUTTERFLY", "CHOCOLATE PANSY", "COMMON GRASS YELLOW", "FRUIT PIERCING MOTH", "LIME BUTTERFLY", "PEACOCK PANSY", "PLAIN TIGER BUTTERFLY", "SHORT BANDED SAILOR", "YELLOW PALM DART BUTTERFLY", "HÜBNER'S WASP MOTH", "GARDEN LIZARD", "TABBY CAT", "PLANTAIN SQUIRREL", "FRUIT BAT"] 

    } 

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






    // MARK: - Table view data source 

    override func numberOfSections(in tableView: UITableView) -> Int { 
     return rainforestCategory.count 
    } 


    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
     let categoryName = rainforestCategory[section] 
     return categoryName.name 
    } 


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     let categoryRows = rainforestCategory[section] 
     return categoryRows.models.count 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     // Table view cells are reused and should be dequeued using a cell identifier. 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! RainforestTableViewCell 

     let row = indexPath.row 
     let section = indexPath.section 

     let categoryName = rainforestCategory[indexPath.section] 
     let organism = categoryName.models[indexPath.row] 

     cell.configureCellWith(organism) 

     return cell 
    } 


    // MARK: - Changing from Table view data source to Details view 

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 


     let storyboard = UIStoryboard(name: "Main", bundle: nil) 
     let detailsVC = storyboard.instantiateViewController(withIdentifier: "RainforestDetailsViewController")as! RainforestDetailsViewController 
     self.navigationController?.pushViewController(detailsVC, animated: true) 





     detailsVC.getName = names[indexPath.row] as! String 
     detailsVC.getScientificName = scientificNames[indexPath.row] as! String 
     detailsVC.getDescription = descriptions[indexPath.row] as! String 



    } 






} 

DetailsViewController.swift

class RainforestDetailsViewController: UIViewController, UIScrollViewDelegate { 


    var zen: Model? 

    var getName = String() 
    var getScientificName = String() 
    var getImage = UIImage() 
    var getDescription = String() 


    @IBOutlet weak var pictureScrollView: UIScrollView! 
    @IBOutlet weak var picturePageControl: UIPageControl! 
    @IBOutlet weak var pictureDescription: UILabel! 
    @IBOutlet weak var pictureName: UILabel! 
    @IBOutlet weak var pictureScientificName: UILabel! 


    let picture1 = ["image":"White Collared Kingfisher (Picture)"] 
    let picture2 = ["image":""] 
    let picture3 = ["image":""] 

    var pictureArray = [Dictionary<String,String>]() 

    func scrollViewDidScroll(_ scrollView: UIScrollView) { 
     let page = scrollView.contentOffset.x/scrollView.frame.size.width 
     picturePageControl.currentPage = Int(page) 
    } 

    func loadPictures() { 

     for (index, picture) in pictureArray.enumerated() { 

      if let pictureView = Bundle.main.loadNibNamed("Picture", owner: self, options: nil)?.first as? PictureView { 

       pictureView.picture.image = UIImage(named: picture["image"]!) 
       pictureScrollView.addSubview(pictureView) 
       pictureView.frame.size.width = self.view.bounds.size.width 
       pictureView.frame.origin.x = CGFloat(index) * self.view.bounds.size.width 

      } 
     } 

    } 


    override func viewDidLoad() { 
     super.viewDidLoad() 

     // pictureScrollView.image = getImage 
     pictureName.text! = getName 
     pictureScientificName.text! = getScientificName 
     pictureDescription.text! = getDescription 







     pictureArray = [picture1,picture2,picture3] 
     pictureScrollView.isPagingEnabled = true 
     pictureScrollView.contentSize = CGSize(width: self.view.bounds.width * CGFloat(pictureArray.count), height: 210) 
     pictureScrollView.showsHorizontalScrollIndicator = false 
     pictureScrollView.delegate = self 

     loadPictures() 

    } 







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





} 
+0

読み下さい値を割り当てる必要があります[どのような状況下で、私はより速く答えを得るために、私の質問に、「緊急」または他の同様の句を追加できますか?](// meta.stackoverflow.com/q/326569 ) - 要約は、これはボランティアに対処する理想的な方法ではなく、おそらく回答を得ることには非生産的であるということです。これをあなたの質問に追加しないでください。 – halfer

答えて

0

確認してください:前あなたを押す

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let storyboard = UIStoryboard(name: "Main", bundle: nil) 

    let detailsVC = storyboard.instantiateViewController(withIdentifier: "RainforestDetailsViewController")as! RainforestDetailsViewController 
    detailsVC.getName = names[indexPath.row] as! String 
    detailsVC.getScientificName = scientificNames[indexPath.row] as! String 
    detailsVC.getDescription = descriptions[indexPath.row] as! String 

    self.navigationController?.pushViewController(detailsVC, animated: true) 
} 
関連する問題