【发布时间】:2016-12-16 04:23:35
【问题描述】:
我有一个UITableView,它显示了一个用户列表。如果在返回的 JSON 中他们的display_name 是null,则显示他们的socialNetworkHandle。但是,当我设置要修剪的空格时,我无法弄清楚为什么有些用户的 displayName 在字符串的开头包含空格。
首先是保存用户信息的结构:
internal struct UserInformation {
let socialNetworkHandle: String
var displayName: String? = nil
internal init?(socialNetworkHandle: String, displayName: String? = nil) {
self.socialNetworkHandle = socialNetworkHandle
self.displayName = displayName
}
}
接下来是我解析 JSON 以创建用户信息结构的代码:
private func userInformation(from jsonDictionary: JSONDictionary) -> FeedwallPost.UserInformation? {
// ...Some parsing code...
var userInformation = Post.UserInformation()
if let displayName = jsonDictionary["display_name"] as? String {
userInformation?.displayName = displayName
} else {
print("`displayName` is not of type `String`")
}
// ...Some parsing code...
return userInformation
}
最后,我在单元格中显示用户的displayName 或socialNetworkHandle。如果displayName 是nil,则显示socialNetworkHandle:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
/// ...Cell configuration code...
cell.textLabel?.text = post.userInformation.displayName?.trimmingCharacters(in: .whitespaces) ?? post.userInformation.socialNetworkHandle.trimmingCharacters(in: .whitespaces)
/// ... Cell configuration code...
return cell
}
我一直遇到的问题是,当我修剪它以供显示时,用户在其displayName 的开头显示为空格。以下屏幕截图说明了正在发生的事情:
谁能告诉我我做错了什么?
【问题讨论】:
-
你想用 Objc 还是 Swift 做出答案?
标签: ios string uitableview removing-whitespace