我是 Swift 开发的新手,我正在开发一个将 JSON 文件解析为 UITableView 内的 CustomCell 的项目。我遇到的问题是我的标签是空的(因为我可以选择展开),如果是空的,我不希望它们显示在我的单元格中。这是我的代码:
import UIKit
class ScheduleTableViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var myTableView: UITableView!
var nodeCollection = [Node]()
var service:NodeService!
override func viewDidLoad() {
super.viewDidLoad()
service = NodeService()
service.getNodes {
(response) in
self.loadNodes(response["nodes"] as! NSArray)
}
}
func loadNodes(nodes:NSArray){
for node in nodes {
var node = node["node"]! as! NSDictionary
var field_class_day_value = node["field_class_day_value"] as! String
var field_class_time_start_value = node["field_class_time_start_value"] as! String
var field_class_time_end_value = node["field_class_time_end_value"] as! String
var field_class_flex_header_value = node["field_class_flex_header_value"] as! String
var title = node["title"] as!String
var field_ages_value = node["field_ages_value"] as? String
var field_class_footer_value = node["field_class_footer_value"] as? String
var field_class_flex_footer_value = node["field_class_flex_footer_value"] as! String
var field_class_instructor_nid = node["field_class_instructor_nid"] as? String
if (field_class_day_value == "1"){
field_class_day_value = "Monday"
}else if (field_class_day_value == "2"){
field_class_day_value = "Tuesday"
}else if (field_class_day_value == "3"){
field_class_day_value = "Wednesday"
}else if (field_class_day_value == "4"){
field_class_day_value = "Thrusday"
}else if (field_class_day_value == "5"){
field_class_day_value = "Friday"
}else if (field_class_day_value == "6"){
field_class_day_value = "Saturday"
}else{
field_class_day_value = "Sunday"
}
//convert time
var dataStringStartTime = field_class_time_start_value
var dataStringEndTime = field_class_time_end_value
var dateFormatter = NSDateFormatter()
var dateFormatter2 = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter2.dateFormat = "h:mm a"
let dateValueStartTime = dateFormatter.dateFromString(dataStringStartTime) as NSDate!
let dateValueEndTime = dateFormatter.dateFromString(dataStringEndTime) as NSDate!
let class_time_start_value = dateFormatter2.stringFromDate(dateValueStartTime)
let class_time_end_value = dateFormatter2.stringFromDate(dateValueEndTime)
let class_time_final = "\(class_time_start_value) - \(class_time_end_value)"
let title_final = title.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
var nodeObj = Node(field_class_day_value: field_class_day_value,
class_time_final: class_time_final,
field_class_flex_header_value: field_class_flex_header_value,
title_final: title_final,
field_ages_value: field_ages_value,
field_class_footer_value: field_class_footer_value,
field_class_flex_footer_value: field_class_flex_footer_value,
field_class_instructor_nid: field_class_instructor_nid)
nodeCollection.append(nodeObj)
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nodeCollection.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : CustomCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
let node = nodeCollection[indexPath.row]
cell.lbl_day_value.text = node.field_class_day_value
cell.lbl_class_time_final.text = node.class_time_final
cell.lbl_flex_header_value.text = node.field_class_flex_header_value
cell.lbl_title.text = node.title_final
cell.lbl_ages_value.text = node.field_ages_value
cell.lbl_footer_value.text = node.field_class_footer_value
cell.lbl_flex_footer_value.text = node.field_class_flex_footer_value
cell.lbl_instructor_nid.text = node.field_class_instructor_nid
return cell
}
}
最佳答案
你可以试一试:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : CustomCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
let node = nodeCollection[indexPath.row]
cell.lbl_day_value.text = node.field_class_day_value
cell.lbl_class_time_final.text = node.class_time_final
cell.lbl_flex_header_value.text = node.field_class_flex_header_value
cell.lbl_title.text = node.title_final
cell.lbl_ages_value.text = node.field_ages_value
cell.lbl_footer_value.text = node.field_class_footer_value
cell.lbl_flex_footer_value.text = node.field_class_flex_footer_value
cell.lbl_instructor_nid.text = node.field_class_instructor_nid
//Get all your labels and check if they are now empty
for view in cell.subviews {
if let label = view as? UILabel {
if label.text!.isEmpty {
label.hidden = true
}
else {
label.hidden = false
}
}
}
return cell
}
此外,作为一种标准做法,当您有这样的 elseif 时,使用 switch 看起来会好很多:
switch field_class_day_value {
case "1":
field_class_day_value = "Monday"
case "2":
field_class_day_value = "Tuesday"
case "3":
field_class_day_value = "Wednesday"
case "4":
field_class_day_value = "Thrusday"
case "5":
field_class_day_value = "Friday"
case "6":
field_class_day_value = "Saturday"
default:
field_class_day_value = "Sunday"
}
此处示例:https://mega.nz/#!Q1xT3YJR!TP_BOCBVt6mCg1YAafo6EHQKIPqYKzT6scU6ZAPtgWg
关于json - swift : Hide Labels if Empty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31821946/
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":
我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("
我在一个简单的RailsAPI中有以下Controller代码:classApi::V1::AccountsControllerehead:not_foundendendend问题在于,生成的json具有以下格式:{id:2,name:'Simpleaccount',cash_flows:[{id:1,amount:34.3,description:'simpledescription'},{id:2,amount:1.12,description:'otherdescription'}]}我需要我生成的json是camelCase('cashFlows'而不是'cash_flows'
我正在学习如何使用JSONgem解析和生成JSON。我可以轻松地创建数据哈希并将其生成为JSON;但是,在获取一个类的实例(例如Person实例)并将其所有实例变量放入哈希中以转换为JSON时,我脑袋放屁。这是我遇到问题的例子:require"json"classPersondefinitialize(name,age,address)@name=name@age=age@address=addressenddefto_jsonendendp=Person.new('JohnDoe',46,"123ElmStreet")p.to_json我想创建一个.to_json方法,这样我就可以获
我正在构建一个带有Rails后端的JS应用程序,为了不混淆snake和camelcases,我想通过从服务器返回camelcase键名来规范化这一切。因此,当从API返回时,user.last_name将返回user.lastName。我如何实现这一点?谢谢!编辑:添加Controller代码classApi::V1::UsersController 最佳答案 我的方法是使用ActiveModelSerializer和json_api适配器:在你的Gemfile中,添加:gem'active_model_serializers'创建
我有以下内容:@array.inspect["x1","x2","adad"]我希望能够将其格式化为:client.send_message(s,m,{:id=>"x1",:id=>"x2",:id=>"adad"})client.send_message(s,m,???????)如何在????????中获得@array输出?空间作为ID?谢谢 最佳答案 {:id=>"x1",:id=>"x2",:id=>"adad"}不是有效的散列,因为您有键冲突它应该是这样的:{"ids":["x1","x2","x3"]}更新:@a=["x1
这里我想输出带有动态组名的json而不是单词组@tickets.eachdo|group,v|json.group{json.array!vdo|ticket|json.partial!'tickets/ticket',ticket:ticketend}end@ticket是这样的散列{a:[....],b:[.....]}我想要这样的输出{a:[.....],b:[....]} 最佳答案 感谢@AntarrByrd,这个问题有类似的答案:JBuilderdynamickeysformodelattributes使用上面的逻辑我已经
我正在寻找一种将“json”散列展平为展平散列但将路径信息保留在展平键中的方法。例如:h={"a"=>"foo","b"=>[{"c"=>"bar","d"=>["baz"]}]}flatten(h)应该返回:{"a"=>"foo","b_0_c"=>"bar","b_0_d_0"=>"baz"} 最佳答案 这应该可以解决您的问题:h={'a'=>'foo','b'=>[{'c'=>'bar','d'=>['baz']}]}moduleEnumerabledefflatten_with_path(parent_prefix=nil)
Ruby中如何“一般地”计算以下格式(有根、无根)的JSON对象的数量?一般来说,我的意思是元素可能不同(例如“标题”被称为其他东西)。没有根:{[{"title":"Post1","body":"Hello!"},{"title":"Post2","body":"Goodbye!"}]}根包裹:{"posts":[{"title":"Post1","body":"Hello!"},{"title":"Post2","body":"Goodbye!"}]} 最佳答案 首先,withoutroot代码不是有效的json格式。它将没有包