Swift Я не могу добавить конец подстроки variableString, значение остается прежним, что не так? - PullRequest
0 голосов
/ 27 мая 2018
import UIKit
import FirebaseDatabase
import FirebaseStorage
import Firebase

class LoginController: UIViewController, UIImagePickerControllerDelegate,UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource{

    var ref: DatabaseReference!
    let cellID = "cellID"

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3}

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath)

        let secim = indexPath
        if secim == [0, 0] {
            cell.backgroundColor = UIColor (r: 242, g: 182, b: 50)
        }
        if secim == [0, 1] {
            cell.backgroundColor = UIColor (r: 63, g: 176, b: 174)
        }
        if secim == [0, 2] {
            cell.backgroundColor = UIColor (r: 23, g: 62, b: 67)
        }
        cell.layer.cornerRadius = 20
        cell.layer.masksToBounds = true
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //print("Selected cell: \(indexPath)")
        let secim = indexPath
        var variableString = "Horse"

        if(secim == [0, 0]){
         variableString.insert("b", at: variableString.endIndex)
        }

        else if(secim == [0, 1]){
         variableString.insert("b", at: variableString.endIndex)
        }

        else if(secim == [0, 2]){
           variableString.insert("c", at: variableString.endIndex)
        }
        print(variableString)
    }

enter image description here

1 Ответ

0 голосов
/ 27 мая 2018

Согласно вашей логике, он должен добавлять символ в конец строки, потому что var variableString = "Horse" является локальным объектом в методе didSelect.

Вы можете сделать это следующим образом:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    //print("Selected cell: \(indexPath)")
    let secim = indexPath
    var variableString = "Horse" //This is local object and will change when again this method call

    if(secim == [0, 0]){
     variableString.insert("a", at: variableString.endIndex)
    }

    else if(secim == [0, 1]){
     variableString.insert("ab", at: variableString.endIndex)
    }

    else if(secim == [0, 2]){
       variableString.insert("abc", at: variableString.endIndex)
    }
    print(variableString)
}

Или

Вы должны добавить этот объект глобально.(Если вы собираетесь создать глобально этот объект, вам придется управлять вставкой и удалением обоих)

...