这里需要做的是通过使用NSMutableAttributedString在表格视图中删除一个任务。问题是我不知道如何在数组上应用这种效果/确定数组中的任务。
一切正常,但我不知道如何以正确的方式应用最后一行。
// name.attributedText = attributeString;
import RealmSwift
import Foundation
import Realm
class Task: Object {
@objc dynamic var id = UUID().uuidString
@objc dynamic var name: String?
@objc dynamic var isFinished = false
override static func primaryKey() -> String? {
return "id"
}
convenience init(id: String, name: String, isFinished: Bool) {
self.init()
self.id = id
self.name = name
self.isFinished = isFinished
}
var realm: Realm!
var taskArray: Results<Task>!
override func viewDidLoad() {
super.viewDidLoad()
self.realm = try! Realm()
self.taskArray = realm.objects(Task.self)
}
func saveAction(name: String) {
let task = Task(id: UUID().uuidString, name: name, isFinished: false)
try! self.realm.write {
self.realm.add(task)
}
taskTableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! UITableViewCell
let task = taskArray[indexPath.row]
cell.textLabel?.text = task.name
let taskSwitch = UISwitch(frame: CGRect(x: 1, y: 1, width: 20, height: 20))
taskSwitch.isOn = false
taskSwitch.addTarget(self, action: #selector(updateLabel(_:)), for: .valueChanged)
cell.accessoryView = taskSwitch
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: task.name!)
if taskSwitch.isOn == true {
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
//name.attributedText = attributeString;
}
return cell
}