【发布时间】:2016-09-17 18:56:36
【问题描述】:
我刚刚开始使用 Swift,但我在自定义 UITableViewCell 时遇到了一些奇怪的问题。问题是我需要在每个表格单元格内有一个白色背景,如 here 所示。
我创建了一个自定义 UITableViewCell 类,并为图像、标签和按钮创建了 IBOutlets,如下所示:
import UIKit
class LocationTableViewCell: UITableViewCell {
@IBOutlet var locationImageView: UIImageView!
@IBOutlet var locationButton: UIButton!
@IBOutlet var locationLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
我的视图控制器代码是:
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet var locationTableView: UITableView!
var skiLocation = Location(name: "Banff", picture: UIImage(named: "ski.jpeg")!)
var tundraLocation = Location(name: "Yellowknife", picture: UIImage(named: "tundra.jpeg")!)
var beachLocation = Location(name: "Cancun", picture: UIImage(named: "beach.jpeg")!)
var locations: [Location] = []
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return locations.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: LocationTableViewCell = tableView.dequeueReusableCellWithIdentifier("location", forIndexPath: indexPath) as! LocationTableViewCell
cell.locationLabel.text = self.locations[indexPath.row].name
cell.locationImageView.image = self.locations[indexPath.row].picture
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locations = [skiLocation, tundraLocation, beachLocation]
self.locationTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我通过在每个表视图中创建一个 UIView,然后将按钮、标签和图像放置在 UIView 中来解决这个问题。这只是为了获得白色背景。但是,当我运行我的代码时,一切都按预期显示,除了没有 UILabel 并且 UIButton 按照情节提要进行了风格化。当我尝试通过情节提要更改标签的背景或按钮时,没有任何变化。没有标签,只有通用按钮。奇怪的是我可以通过 ViewController 类将图像设置为 UIImageView。
有什么想法吗?
编辑:Here 是故事板视图的链接。我已使用情节提要视图中的标识符字段来链接单元格。
【问题讨论】:
-
你能在 IB 中展示你的单元格吗?
-
@AlexKosyakov Here 是我故事板的截图。这有帮助吗?
-
我看不到,您是否对标签和按钮的超级视图设置了约束?
-
并在self.locationTableView.dataSource = self之后添加tableView.reloadData()
-
@AlexKosyakov 不知道为什么截图不起作用?在我这边工作。是的,我已经限制了按钮和标签。该按钮显示在正确的位置,这是完全标准的。没有我通过情节提要添加的颜色或样式。
标签: ios swift uitableview uiview storyboard