如何替换字符串的前两个单词?

问题描述 投票:0回答:0

  1. 我有两个 viewController(FirstVC 和 SecondVC),每个都包含 tableView(firstTableView 和 secondTableView)。
  2. 当一个人点击第一个 TableView 中的一个单元格时,他/她将转换到 SecondVC,其中 secondTableView 上方是一个带有字符串 (secondName) 的 UIView。该字符串继承了 FirstVC 的 firstTableView 上单元格的文本。
  3. secondName 中的文本必须按照代码所示进行更改。
  4. 感谢@Leo Dabus 在 SO 上的回答,我设法创造了只替换字符串中第一个单词的条件。
  5. 但是,我还需要能够替换前两个词。例如,考虑第一个单词是“Justin Gaethje”而不仅仅是“Gaethje”的情况。在这种情况下,我需要替换这两个词。

此外,我意识到可能有一些更优雅的方法来进行替换,但请注意,由于应用程序语言的语法细节,我必须这样做。

这是 SecondVC 的代码:

import UIKit

class SecondVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var secondTableView: UITableView!

var secondVCNames: [SecondCellModel] = []

var textForChanging: String = ""

var switchedFirstWord: String {
    switch textForChanging.firstWord {
    case "Gaethje": return "Dustin Porier"
    default: return "none" } }

var restoOfTheName: String {
    var string = textForChanging
    string.enumerateSubstrings(in: string.startIndex..., options: .byWords) { (_, _, enclosingRange, stop) in
        string.removeSubrange(enclosingRange)
        stop = true }
    return string }

var adjustedEventNameText: String {
    return switchedFirstWord + " " + restoOfTheName }

override func viewDidLoad() {
    super.viewDidLoad()
    secondTableView.delegate = self
    secondTableView.dataSource = self
    
    secondVCNames = [
        (SecondCellModel(secondNameModel: "Something...")),
        (SecondCellModel(secondNameModel: "Something...")),
        (SecondCellModel(secondNameModel: "Something...")),
        (SecondCellModel(secondNameModel: "Dark Side...")) ]
    
    let tableHeader = UIView()
    secondTableView.tableHeaderView = tableHeader
    
    let secondLabel = UILabel(frame: tableHeader.bounds)
    secondLabel.translatesAutoresizingMaskIntoConstraints = false
    secondLabel.text = "Imagine if \(adjustedEventNameText)"
    secondLabel.font = UIFont(name:"Arial-BoldMT", size: 17.0)
    secondLabel.numberOfLines = 0
    secondLabel.lineBreakMode = .byWordWrapping
    secondLabel.textAlignment = .center
    secondLabel.translatesAutoresizingMaskIntoConstraints = false

    tableHeader.addSubview(secondLabel)
    
    let g = tableHeader.layoutMarginsGuide
    
    NSLayoutConstraint.activate([
        secondLabel.topAnchor.constraint(equalTo: g.topAnchor, constant: 11.0),
        secondLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
        secondLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0)])
    
    let c = secondLabel.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -11.0)
    c.priority = .required - 1
    c.isActive = true }

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if let tableHeader = secondTableView.tableHeaderView {
        let fitSize: CGSize = CGSize(width: secondTableView.frame.width, height: .greatestFiniteMagnitude)
        let sz: CGSize = tableHeader.systemLayoutSizeFitting(fitSize, withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow)
        let height: CGFloat = sz.height
        var headerFrame = tableHeader.frame
        if height != headerFrame.size.height {
            headerFrame.size.height = height
            tableHeader.frame = headerFrame
            secondTableView.tableHeaderView = tableHeader } } }

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = secondTableView.dequeueReusableCell(withIdentifier: "secondCell", for: indexPath) as! SecondCell
    let Name = secondVCNames[indexPath.row]
    cell.secondLabel.text = Name.secondNameModel
    return cell } }

// code borrowed from Leo Dabus as an answer to a different question
extension StringProtocol {
var byWords: [SubSequence] { components(separated: .byWords) }

func components(separated options: String.EnumerationOptions)-> [SubSequence] {
    var components: [SubSequence] = []
    enumerateSubstrings(in: startIndex..., options: options) { _, range, _, _ in components.append(self[range]) }
    return components }

var firstWord: SubSequence? {
    var word: SubSequence?
    enumerateSubstrings(in: startIndex..., options: .byWords) { _, range, _, stop in
        word = self[range]
        stop = true }
    return word } }

还有 FirstVC 的代码:

import UIKit

class FirstVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var firstTableView: UITableView!

var names: [FirstCellModel] = []

override func viewDidLoad() {
    super.viewDidLoad()
    firstTableView.delegate = self
    firstTableView.dataSource = self
    
    names = [
    FirstCellModel(firstNameModel: "Gaethje could beat Charles Oliveira"),
    FirstCellModel(firstNameModel: "..."),
    FirstCellModel(firstNameModel: "...")
    ]
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    firstTableView.deselectRow(at: indexPath, animated: true)
    if let vc = storyboard?.instantiateViewController(withIdentifier: "SecondVC") as? SecondVC {
        vc.textForChanging = names[indexPath.row].firstNameModel!
        self.navigationController?.pushViewController(vc, animated: true) } }

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = firstTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
    let Name = names[indexPath.row]
    cell.nameLabel.text = Name.firstNameModel
    return cell }
}
ios swift substring tableview
© www.soinside.com 2019 - 2024. All rights reserved.