【发布时间】:2015-10-29 20:40:31
【问题描述】:
我对这个应用程序的想法:创建一个用户列表,其中包含基于额外信息的职位。
我的编码:
为了显示列表,我使用带有动态表格视图单元格高度和自动布局的 UITableView。因为所有单元格都有几乎相同的子视图(例如:头像、全名、描述),所以我只想使用 1 个自定义 UITableViewCell 来显示用户信息。
这是 CustomCell.xib 的图像:Custom Cell + Extra Info Constraints
Extra Info 是 UIView,我将用每种工作类型的正确额外信息替换它(例如:摄影师的 UIImageView、显示作者书籍列表的 UITextField 等)。
当我从数据库或 API 加载用户数据时,我只用代码为 CustomCell 类分配每一行:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(customCellIdentifier) as! CustomCell
cell.userData = allUserData[indexPath.row] as NSDictionary
return cell
}
这是CustomCell类的代码(我删除了设置头像,全名,描述的代码以使帖子更短):
class CustomCell: UITableViewCell {
var userData: NSDictionary! {
didSet {
updateContent()
}
}
function updateContent() {
if let userType = userData["job_type"] as? String {
if (userType == "Photographer") {
// I think I was wrong with this code
let photographerContentView = PhotographerView()
photographerContentView.mainImage = UIImage(name: userData["image"] as String)
self.extraInfoView = photographerContentView
} else {
// I have a lot job types need to check
}
}
}
}
PhotographerView 是自定义 UIView,我将从带有设置自动布局的 xib 文件中加载它
class PhotographerView: UIView {
@IBOutlet var mainImage: UIImage!
var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "PhotographerView", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
}
问题:
- 我无法使用 Auto Layout 的新数据绘制 PhotographerContentView 并将其分配给 extraInfoView
- 我知道我可以通过为每个用户作业类型(如Dynamic Table View Cell Height and Auto Layout)创建一个新的自定义 UITableViewCell 来完成我的应用程序。但如果我这样做了,当我需要添加更多相同的子视图(如地址、电话号码等)时,我将不得不更改所有自定义 xib 文件。
- 我知道 UIView 在 Apple Docs 的 Auto Layout Guide 中没有内在内容大小,但我需要使用 Auto Layout 呈现自定义视图并将其添加到具有全屏宽度的父视图的方法(也许我需要以编程方式添加约束)。
我的问题的最佳解决方案是什么?你能给我一些示例代码吗?
谢谢!
【问题讨论】:
标签: ios iphone swift uitableview autolayout