Swift 2에서 데이터를 다시로드 할 때 테이블 형식이 변경되지 않도록하려면 어떻게해야합니까?

제이슨 슐츠

내 UITableView의 초기 모습은 다음과 같습니다. 보시다시피 멋져 보입니다. :

여기에 이미지 설명 입력

데이터가 다시로드되면 다음과 같이 표시됩니다 (좋지 않음).

여기에 이미지 설명 입력

내 Realm.io 객체는 다음과 같습니다.

import RealmSwift
import Foundation

class Set: Object {

    dynamic var id = NSUUID().UUIDString
    dynamic var set_id = ""
    dynamic var descr = ""
    dynamic var img_sm = ""
    dynamic var img_tn = ""
    dynamic var pieces = ""
    dynamic var qty = ""
    dynamic var theme = ""
    dynamic var year = ""

    // Specify properties to ignore (Realm won't persist these)

    //  override static func ignoredProperties() -> [String] {
    //    return []
    //  }

    override static func primaryKey() -> String? {
        return "id"
    }
}

사용자에게 몇 가지 옵션을 선택할 수있는 알림을 통해 테이블 ​​정렬을 변경할 수있는 옵션을 제공합니다.

func showSorting(errorTitle:String, errorMessage:String) {
    let alert = UIAlertController(title: "\(errorTitle)", message: "\(errorMessage)", preferredStyle: .Alert) // 1
    let firstAction = UIAlertAction(title: "Sort by Set Number", style: .Default) { (alert: UIAlertAction!) -> Void in
        NSLog("Sorting by Number")

        self.array = try! Realm().objects(Set).sorted("set_id", ascending: true)
        self.tableView.reloadData()

    } // 2
    alert.addAction(firstAction) // 4

    let secondAction = UIAlertAction(title: "Sort by Set Name", style: .Default) { (alert: UIAlertAction!) -> Void in
        NSLog("Sorting by Name")
        self.array = try! Realm().objects(Set).sorted("descr", ascending: true)
        self.tableView.reloadData()
    } // 3

    alert.addAction(secondAction) // 5

    presentViewController(alert, animated: true, completion:nil) // 6
}

아주 간단한 것입니다. Realm 객체를 가져 와서 원하는 방법으로 정렬 한 다음 테이블을 다시로드합니다. 일을 엉망으로 만드는 것은 데이터를 다시로드하는 것입니다.

표보기 셀에 자막 스타일을 사용하고 있습니다.

셀이 렌더링되는 방법은 다음과 같습니다.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

    let imageView = cell.viewWithTag(30) as! UIImageView

    let Title = cell.viewWithTag(10) as! UILabel

    let subTitle = cell.viewWithTag(20) as! UILabel

    Title.textColor = UIColor.whiteColor()
    subTitle.textColor = UIColor.whiteColor()
    cell.backgroundColor = UIColor(red: 0.7176, green: 0.1647, blue: 0.2, alpha: 1.0) /* #b72a33 */

    let object = array[indexPath.row]

    let img_url = object.img_sm
    cell.textLabel?.text = object.set_id

    imageView.contentMode = .ScaleAspectFit

    if let checkedUrl = NSURL(string: "\(img_url)") {
        imageView.contentMode = .ScaleAspectFit

        getDataFromUrl(checkedUrl) { (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()) { () -> Void in
                guard let data = data where error == nil else { return }
                imageView.image = UIImage(data: data)
            }
        }
    }

    subTitle.text = object.descr

    return cell
}

I hope this helps. I'm not sure what I'm doing wrong that's screwing it up? Thank you for your help, I greatly appreciate it! :)

matt
  1. Remember that when the cells are reloaded, they are reused. Every aspect of the cell must be reset afresh; otherwise it may be left over from its previous use.

  2. It looks like you're trying to do some sort of networking inside cellForRowAtIndexPath. You can't do that. You must return the cell right now. If your data requires networking, return a placeholder and do the networking separately (and reload the cells when you don't need to do any networking).

Thus, for example, this code is wrong:

if let checkedUrl = NSURL(string: "\(img_url)") {
    imageView.contentMode = .ScaleAspectFit

    getDataFromUrl(checkedUrl) { (data, response, error)  in
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            guard let data = data where error == nil else { return }
            imageView.image = UIImage(data: data)
        }
    }
}

네트워킹 지연 후 이와 같이 셀의 어떤 측면도 직접 변경해서는 안됩니다. 아시다시피 세포는 그때까지 존재하지 않을 수도 있습니다. 네트워크에서 데이터를 가져 오려면 모델 로 가져온 다음 테이블을 다시로드하면됩니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관