子类化SLKTextViewController

时间:2015-05-14 02:10:23

标签: swift

我有一个ViewController,其tableview可以正常运行。

现在我正在尝试子类SLKTextViewController,但应用程序现在崩溃了。我是否错误地将其子类化(在this example之后)?

SLKTextViewController SubClass:

import UIKit

class CommentsTextViewController: SLKTextViewController {

    var foodPhotoObject: PFObject?
    var userNameText = ""
    var distanceLabelText = ""
    var userPhotoUIImage: UIImage?
    var mainRestaurantUIImage: UIImage?

    // get comment arrays
    var photoCommentObjects: [AnyObject] = []
    var commentUsers: [PFUser] = []
    var commentText: [String] = []

    @IBOutlet var mainRestaurantImageView: PFImageView!
    @IBOutlet var userPhoto: UIImageView!
    @IBOutlet var userName: UIButton!
    @IBOutlet weak var distanceLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        setupTableViewCells()

        // load comments
        fetchComments()
        self.tableView.registerClass(CommentsCell.self, forCellReuseIdentifier: "CommentCell")
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 80
        self.tableView.backgroundColor = UIColor.clearColor()
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.scrollsToTop = true
        self.bounces = true
        self.keyboardPanningEnabled = true
        self.inverted = true
        self.tableView.frame = self.view.frame
        self.textView.placeholder = "Comment"
        self.textView.placeholderColor = UIColor(red: 0.75, green: 0.75, blue: 0.75, alpha: 1)
        self.textView.layer.borderColor = UIColor(red: 0.75, green: 0.75, blue: 0.75, alpha: 1).CGColor
        self.textView.pastableMediaTypes = SLKPastableMediaType.None
        self.rightButton.setTitle("Post", forState: UIControlState.Normal)
        self.textInputbar.autoHideRightButton = true
        self.textInputbar.maxCharCount = 140
        self.textInputbar.counterStyle = SLKCounterStyle.Split
//        // Do any additional setup after loading the view.
    }

    func setupTableViewCells() {
        userName.setTitle(userNameText, forState: .Normal)
        distanceLabel.text = distanceLabelText
        userPhoto.image = userPhotoUIImage
        // make profile photo circular
        userPhoto.layer.cornerRadius = userPhoto.frame.size.width / 2;
        userPhoto.layer.masksToBounds = true;
        userPhoto.layer.borderWidth = 0 // remove border

        mainRestaurantImageView.image = mainRestaurantUIImage
        mainRestaurantImageView.contentMode = .ScaleAspectFill
        mainRestaurantImageView.clipsToBounds = true

        tableView.estimatedRowHeight = 44.0
        tableView.rowHeight = UITableViewAutomaticDimension
    }

    func fetchComments() {

        var query = PFQuery(className:"Activity") //default: Restaurant
        query.whereKey("Photo", equalTo:foodPhotoObject!) // find photos equal to
        query.whereKey("Type", equalTo:"Comment")
        query.includeKey("FromUser")
        query.orderByDescending("createdAt")
        query.findObjectsInBackgroundWithBlock {
            (objects: [AnyObject]?, error: NSError?) -> Void in
            if objects!.isEmpty { //if objects != nil {
                //NO RESULTS
                println("NO COMMENTS FOUND") //allow user to input zipcode
                // check if activity indicator is animating
                self.stopActivityIndicator()
            } else {
                println(objects)
                self.photoCommentObjects = objects!

                self.commentUsers = self.photoCommentObjects.map { $0.objectForKey("FromUser") as! PFUser }
                self.commentText = self.photoCommentObjects.map { $0.objectForKey("Content") as! String }

                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.tableView.reloadData()
                })
            }
        }
    }

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("CommentCell", forIndexPath: indexPath) as! CommentsCell
        // START: Get comment date
        let dateCreated = photoCommentObjects[indexPath.row].createdAt as NSDate!
        let dateFormat = NSDateFormatter()
        dateFormat.dateFormat = "EEE, MMM d, h:mm a"
        dateFormat.dateStyle = .ShortStyle
        dateFormat.timeStyle =  .NoStyle
        dateFormat.doesRelativeDateFormatting = true
        cell.timeLabel.text = NSString(format: "%@", dateFormat.stringFromDate(dateCreated)) as String
        cell.commentLabel.text = commentText[indexPath.row]
        //cell.commentLabel.adjustsFontSizeToFitWidth = true
        cell.commentLabel.preferredMaxLayoutWidth = 300


        // START: Get username out of the PFUser array
        let commentUser: PFUser = self.commentUsers[indexPath.row]
        let commentUserName: String = commentUser.objectForKey("username") as! String

        cell.userName.setTitle(commentUserName, forState: .Normal)



        // START: Get Profile Photo
        // get profile PFFile
        var getProfilePhoto: PFFile! = commentUser.objectForKey("profilePhoto") as? PFFile

        // get UIImage from PFFile
        if (getProfilePhoto != nil) { // if there is a profilephoto
            getProfilePhoto.getDataInBackgroundWithBlock {
                (imageData: NSData?, error: NSError?) -> Void in
                if error == nil {
                    let image = UIImage(data:imageData!)
                    cell.userPhoto.image = image
                    println("this image3 \(image)")

                    //                                self.uploadPhoto.hidden = true // hide "Upload Photo Button"
                    cell.userPhoto.layer.cornerRadius = cell.userPhoto.frame.size.width / 2;
                    cell.userPhoto.layer.masksToBounds = true;
                    cell.userPhoto.layer.borderWidth = 0 // remove border
                }
            }
        } else { // there is no profile photo (use default

            // set default profile photo
            cell.userPhoto.image = UIImage(named: "Tasteup-Icon")
            cell.userPhoto.layer.cornerRadius = cell.userPhoto.frame.size.width / 2;
            cell.userPhoto.layer.masksToBounds = true;
            cell.userPhoto.layer.borderWidth = 0 // remove border
        }

        return cell

    }

    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 80
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.photoCommentObjects.count
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func didPressRightButton(sender: AnyObject!) {
        self.textView.refreshFirstResponder()
        var comment:String = self.textView.text
        self.tableView.beginUpdates()
        self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
        self.tableView.endUpdates()

        self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
        super.didPressRightButton(sender)
    }
}

错误:

2015-05-13 22:04:30.890 App[39965:1524334] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000110e77c65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000011366abb7 objc_exception_throw + 45
    ...
    24  UIKit                               0x000000011239e900 UIApplicationMain + 1282
    25  TasteUp                             0x000000010fdbf077 main + 135
    26  libdyld.dylib                       0x00000001159ab145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

1 个答案:

答案 0 :(得分:1)

你需要     import SlackTextViewController