如何从json调用评级视图并在我的表格视图中显示评级

时间:2016-03-23 19:23:29

标签: ios iphone json swift uitableview

我有一个自定义单元格,因为我有"姓名","地址" "评级视图"。评级视图是评级视图的一个单独的库文件,它将有3个图像(全星,半星,空星)。现在,根据我的json数据,我对每个单元格都有一些评级值。喜欢以下json结构:

这是我的自定义单元格:

class customCell: UITableViewCell {


    @IBOutlet weak var vendorName: UILabel!   // vendor label name

    @IBOutlet weak var vendorAddress: UILabel!   // vendor address aname

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

我的表格视图控制器:

我还有2个自定义单元格。但是如果我尝试添加一个单元格,我将制作并理解代码,我会为所有自定义单元格做。

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

            // if cell tap condition

        if(isTapped == true && indexPath == selectedIndex)
        {



            if (premiumUserCheck && indexPath == selectedIndex ) {

                let cell1:premiumUsercell = self.tableView.dequeueReusableCellWithIdentifier("cell3") as! premiumUsercell

                cell1.phoneNumber = (arrDict[indexPath.section] .valueForKey("phone") as? String)!
                cell1.vendorName3.text=arrDict[indexPath.section] .valueForKey("name") as? String
                cell1.vendorAdddress3.text=arrDict[indexPath.section] .valueForKey("address") as? String

                print("premium user")

                return cell1


            }
            else {

                let cell1:ExpandCell = self.tableView.dequeueReusableCellWithIdentifier("cell2") as! ExpandCell


                cell1.VendorName.text=arrDict[indexPath.section] .valueForKey("name") as? String
                cell1.vendorAdress.text=arrDict[indexPath.section] .valueForKey("address") as? String
                //cell1.externalView.hidden = true

                print("non premium user") 
                return cell1 
            } 
        } 



        // show default cutsom cell

        let cell:customCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! customCell 


        cell.vendorName.text=arrDict[indexPath.section] .valueForKey("name") as? String 
        cell.vendorAddress.text=arrDict[indexPath.section] .valueForKey("address") as? String 

        print("norml user") 



        return cell 
    }

下面的代码是评级视图,是一些库文件,我用它来评级视图。我将自定义视图放在我的自定义单元格中的一个视图下。我必须在自定义单元格中选择我的视图。我必须将该特定类分配为RatingView类。然后,如果我在我的自定义单元格中单击我的评级视图,我可以看到如下图像设置`评级星,星数,关闭,空半图像:

enter image description here

我的ratingviewclasses

import UIKit

@objc public protocol RatingViewDelegate {
    /**
     Called when user's touch ends

     - parameter ratingView: Rating view, which calls this method
     - parameter didChangeRating newRating: New rating
    */
    func ratingView(ratingView: RatingView, didChangeRating newRating: Float)
}

/**
 Rating bar, fully customisable from Interface builder
*/
@IBDesignable
public class RatingView: UIView {

    /// Total number of stars
    @IBInspectable public var starCount: Int = 5

    /// Image of unlit star, if nil "starryStars_off" is used
    @IBInspectable public var offImage: UIImage?

    /// Image of fully lit star, if nil "starryStars_on" is used
    @IBInspectable public var onImage: UIImage?

    /// Image of half-lit star, if nil "starryStars_half" is used
    @IBInspectable public var halfImage: UIImage?

    /// Current rating, updates star images after setting
    @IBInspectable public var rating: Float = Float(0) {
        didSet {
            // If rating is more than starCount simply set it to starCount
            rating = min(Float(starCount), rating)

            updateRating()
        }
    }

    /// If set to "false" only full stars will be lit
    @IBInspectable public var halfStarsAllowed: Bool = true

    /// If set to "false" user will not be able to edit the rating
    @IBInspectable public var editable: Bool = true


    /// Delegate, must confrom to *RatingViewDelegate* protocol
    public weak var delegate: RatingViewDelegate?

    var stars = [UIImageView]()


    override init(frame: CGRect) {
        super.init(frame: frame)

        customInit()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override public func awakeFromNib() {
        super.awakeFromNib()

        customInit()
    }

    override public func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()

        customInit()
    }


    func customInit() {
        let bundle = NSBundle(forClass: RatingView.self)

        if offImage == nil {
            offImage = UIImage(named: "star_empty", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)
        }
        if onImage == nil {
            onImage = UIImage(named: "star_full", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)
        }
        if halfImage == nil {
            halfImage = UIImage(named: "star_half_full", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)
        }

        guard let offImage = offImage else {
            assert(false, "offImage is not set")
            return
        }

        for var i = 1; i <= starCount; i++ {
            let iv = UIImageView(image: offImage)
            addSubview(iv)
            stars.append(iv)

        }

        layoutStars()
        updateRating()
    }

    override public func layoutSubviews() {
        super.layoutSubviews()

        layoutStars()
    }

    func layoutStars() {
        if stars.count != 0,
            let offImage = stars.first?.image {
                let halfWidth = offImage.size.width/2
                let distance = (bounds.size.width - (offImage.size.width * CGFloat(starCount))) / CGFloat(starCount + 1) + halfWidth

                var i = 1
                for iv in stars {
                    iv.frame = CGRectMake(0, 0, offImage.size.width, offImage.size.height)

                    iv.center = CGPointMake(CGFloat(i) * distance + halfWidth * CGFloat(i - 1),
                        self.frame.size.height/2)
                    i++
                }
        }
    }

    /**
     Compute and adjust rating when user touches begin/move/end
    */
    func handleTouches(touches: Set<UITouch>) {
        let touch = touches.first!
        let touchLocation = touch.locationInView(self)

        for var i = starCount - 1; i >= 0; i-- {
            let imageView = stars[i]

            let x = touchLocation.x;

            if x >= imageView.center.x {
                rating = Float(i) + 1
                return
            } else if x >= CGRectGetMinX(imageView.frame) && halfStarsAllowed {
                rating = Float(i) + 0.5
                return
            }
        }

        rating = 0
    }

    /**
     Adjust images on image views to represent new rating
     */
    func updateRating() {
        // To avoid crash when using IB
        if stars.count == 0 {
            return
        }

        // Set every full star
        var i = 1
        for ; i <= Int(rating); i++ {
            let star = stars[i-1]
            star.image = onImage
        }

        if i > starCount {
            return
        }

        // Now add a half star
        if rating - Float(i) + 1 >= 0.5 {
            let star = stars[i-1]
            star.image = halfImage
            i++
        }


        for ; i <= starCount; i++ {
            let star = stars[i-1]
            star.image = offImage
        }
    }
}

// MARK: Override UIResponder methods

extension RatingView {
    override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        guard editable else { return }
        handleTouches(touches)
    }

    override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        guard editable else { return }
        handleTouches(touches)
    }

    override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        guard editable else { return }
        handleTouches(touches)
        guard let delegate = delegate else { return }
        delegate.ratingView(self, didChangeRating: rating)
    }
}

现在我需要从我的json获取评级编号,我必须在我的自定义单元格中分配到我的uiview,我需要在我的所有表格视图单元格中显示相应的评级。

请帮帮我。我很想动态地获取json数据吗?

Thnaks!

更新:

customcell.swift

  @IBOutlet weak var ratingView: RatingView!


    @IBOutlet weak var vendorName: UILabel!   // vendor label name

    @IBOutlet weak var vendorAddress: UILabel!   // vendor address aname

    override func awakeFromNib() {
        super.awakeFromNib()

        super.awakeFromNib()
        //ratingView = RatingView(frame:CGRectMake(0, 0, cellWidth, cellHeight))
        // Initialization code
    }

Viewcontroller.swift

let cell:customCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! customCell 

            let ratingString = "\(arrDict[indexPath.section].valueForKey("rating"))"
            cell.ratingView?.rating = Float(ratingString)!

        cell.vendorName.text=arrDict[indexPath.section] .valueForKey("name") as? String 
        cell.vendorAddress.text=arrDict[indexPath.section] .valueForKey("address") as? String 

1 个答案:

答案 0 :(得分:0)

RatingView的{​​{1}}方法中添加TableViewCell作为子视图,并将其设为全局变量awakeNib。然后

ratingView
var ratingView:RatingView? = nil override func awakeFromNib() { super.awakeFromNib() ratingView = RatingView(frame:CGRectMake(0, 0, cellWidth, cellHeight)) // your requiredFrame }

中的

cellForRowAtIndexPath