【问题标题】:how to call rating view from json and show the rating in my table view如何从 json 调用评级视图并在我的表格视图中显示评级
【发布时间】:2016-07-11 06:19:20
【问题描述】:

我有一个自定义单元格,我有“姓名”、“地址”、“评级视图”。评级视图是一类单独的评级视图库文件,它将有大约 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 类。然后,如果我在自定义单元格中单击我的评分视图,我可以看到如下图来设置`评分星、星数、关闭、空半图像:

我的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 数据??

感谢!

更新:

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 

【问题讨论】:

    标签: ios iphone json swift uitableview


    【解决方案1】:

    TableViewCellawakeNib 方法中添加RatingView 作为子视图,并将其作为全局变量说ratingView。那么

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

    cellForRowAtIndexPath

    let ratingString = "\(arrDict[indexPath.section].valueForKey("rating"))"
    if let ratingValue = Float(ratingString) {
       cell1.ratingView?.rating = ratingValue
    }
    else {
       cell1.ratingView?.rating = 0
    }
    

    【讨论】:

    • 在我的自定义单元格中,我需要将评级视图设置为表格视图单元格的子视图??....你能发布一些相同的代码来说明我的自定义单元格 awakeNib 方法是怎样的吗??跨度>
    • 我在索引路径的单元格行中出现错误,即“无法使用类型为“(AnyObject?)”的参数列表调用类型为“Float”的初始化程序
    • awakefromnib为什么要设置框架??因为我已经设置了视图并添加了约束,并且我已经将名称设置为RatingView作为我的customcell的iboutlet
    • @IBOutlet weak var ratingView: RatingView! override func awakeFromNib() { super.awakeFromNib() super.awakeFromNib() ratingView = RatingView(frame:CGRectMake(0, 0, cellWidth, cellHeight)) // Initialization code }
    • 您是在 xib 文件中连接 ratingView 吗?那为什么还要重新分配呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 2017-01-26
    相关资源
    最近更新 更多