将自定义标签添加到拆分视图中的原型单元格

Adding a custom label to a prototype cell in a split view

我正在 SplitViewController 中开发字典应用程序。在主视图控制器上,我想显示各种输入词和它们被点击的次数,而在细节上,我想显示词的定义和细节。到目前为止,我已经设置了所有内容,除了单词被点击的次数,它应该显示在主视图控制器上。如何在主视图控制器中自定义各种标签,添加标签?

// "Word" class
import UIKit

class Word {
let name: String
let meaning: String
let wordType: String
let numberOfTimesFound: String


init(name: String, meaning: String, wordtype: String, numberOfTimesFound: String) {
    self.name = name
    self.meaning = meaning
    self.wordType = wordtype
    self.numberOfTimesFound = numberOfTimesFound
    }
}


let words = [
Word(name: "Afraid", meaning: "WORD DEFINITION GOES HERE", wordtype: "adjective", numberOfTimesFound: "1")
]

//MasterViewController.swift

import UIKit

class MasterViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()


    let firstWord = words.first

}


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return words.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    let word = words[indexPath.row]
    cell.textLabel?.text = word.name
    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let word = words[indexPath.row]
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.detailViewController.refreshUI(word: word)
}

//AppDelegate.swift

import UIKit

@UIApplicationMain


class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var masterViewController = MasterViewController()
var detailViewController = DetailViewController()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let splitViewController = window?.rootViewController as? UISplitViewController
    let leftNavController = splitViewController!.viewControllers.first as? UINavigationController
    masterViewController = (leftNavController?.topViewController as? MasterViewController)!
    detailViewController = (splitViewController!.viewControllers.last as? DetailViewController)!

    // Override point for customization after application launch.
    return true

}
  • Select 项目导航器中的故事板或笔尖。
  • Select 原型单元格。
  • ⌥⌘4 显示属性检查器。
  • 将单元格的 style 设置为 Right DetailLeft DetailSubtitle 以启用 detailTextLabel 标签。
  • cellForRowAt中将第二个字符串分配给detailTextLabel
  • text属性

如果预定义的样式不符合您的需要,请将样式设置为 custom,将所有 UI 元素拖到单元格中,添加约束,创建一个 UITableViewCell 子class,添加IBOutlets,连接outlets,将cell的class设置为自定义class,将cellForRowAt中出队的cell投射到自定义class.