swift 如何更改字符串中的前两个单词?

e4yzc0pl  于 2023-05-16  发布在  Swift
关注(0)|答案(1)|浏览(89)

这个问题有点难以理解,因为我试图找到一种方法来满足我的应用程序中的外语(俄语,在这种情况下)的语法要求。我试图在俄罗斯的Stackoverflow上找到答案,但它已经死了,一直都是这样。这将是一个很长的阅读,但请忍受我,因为我想让人们理解我在做什么,为什么没有不同的解决方案,除了硬编码一堆逻辑的变通办法。
设置如下:
1.我有两个视图控制器(FirstVC和SecondVC)。
1.每个视图控制器都有一个表。
1.一旦用户点击FirstVC中的单元格,该单元格的内容将传递到SecondVC中的表头视图。
1.但是:SecondVC的表头视图中的文本应该考虑俄语变格(俄语如此困难的原因之一)。

  1. SecondVC的表头视图有两个字符串位于彼此的顶部。上面写着“СПИСОК”,翻译为“列表”。它是静态的,将永远保持原样。下面的一个写着“участников”(翻译为“of participants of the”),后面跟着一个字符串插值。总之,它应该读作“LIST of participants of”,后跟从FirstVC的表单元格继承的任何事件名称。
    这是最难的部分在英语中,你可以在大多数情况下把单词放在一起,然后你就有了一个语法正确的句子。但是俄语在这个意义上是奇怪的,因为你必须修改单词本身来解释变格(我能想到的最接近的类比是当你使用单数和复数时。你不能说:“我喝了两瓶水。你必须在“瓶子”后面加上“s”。差不多吧
    幸运的是,我需要操作的单词通常是字符串中的第一个单词。不过,在更罕见的情况下,可能需要处理字符串中第一个和第二个单词的组合。
    感谢@Leo Dabus在Stackoverflow上的一个回答,我设法从字符串中取出第一个单词,更改它,然后添加到该字符串中的其余单词。现在我需要一种方法来获得字符串的前两个单词,以解决上面提到的那些罕见情况。我怎么能用同样的逻辑来做呢?
    下面是SecondVC的代码:
import UIKit

class SecondVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

var names: [Cell2Model] = []

var textForChanging: String = ""

var switchedFirstWord: String {
    switch textForChanging.firstWord {
    case "Соревнование": return "соревнования" //translates as "competition"
    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()
    tableView.delegate = self
    tableView.dataSource = self
    
    // names will be taken from UITextFields on the fourth view controller
    names = [
        (Cell2Model(name: "Participant 1")),
        (Cell2Model(name: "Participant 2")),
        (Cell2Model(name: "Participant 3")) ]
    
    let tableHeader = UIView()
    tableView.tableHeaderView = tableHeader
    
    let labelOne = UILabel(frame: tableHeader.bounds)
    labelOne.text = "СПИСОК"
    labelOne.font = UIFont(name:"Arial-BoldMT", size: 17.0)
    labelOne.numberOfLines = 0
    labelOne.lineBreakMode = .byWordWrapping
    labelOne.textAlignment = .center
    labelOne.translatesAutoresizingMaskIntoConstraints = false
    
    let labelTwo = UILabel(frame: tableHeader.bounds)
    labelTwo.translatesAutoresizingMaskIntoConstraints = false
    labelTwo.text = "участников \(adjustedEventNameText)"
    labelTwo.font = UIFont(name:"Arial-BoldMT", size: 17.0)
    labelTwo.numberOfLines = 0
    labelTwo.lineBreakMode = .byWordWrapping
    labelTwo.textAlignment = .center
    labelTwo.translatesAutoresizingMaskIntoConstraints = false
    
    tableHeader.addSubview(labelOne)
    tableHeader.addSubview(labelTwo)

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

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if let tableHeader = tableView.tableHeaderView {
        let fitSize: CGSize = CGSize(width: tableView.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
            tableView.tableHeaderView = tableHeader } } }

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

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

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 tableView: UITableView!

var names: [Cell1Model] = []

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
    
    // names will be taken from UITextFields on the third view controller
    names = [
        Cell1Model(name: "Соревнование по легкой атлетике"), // translates as "athletics competition (or "competition on athletics" to put it into the Russian words order)
        Cell1Model(name: "Благотворительное соревнование по легкой атлетике") // translates as "athletics charity competition" (or "charity competition on athletics" in the Russian words order)
    ]
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
    if let vc = storyboard?.instantiateViewController(withIdentifier: "SecondVC") as? SecondVC {
        vc.textForChanging = names[indexPath.row].name!
        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 = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
    let Name = names[indexPath.row]
    cell.label.text = Name.name
    return cell }

感谢您的评分

q8l4jmvw

q8l4jmvw1#

您可以使用拆分(分隔符:“по",maxSplits:1)并且结果数组中的第一个结果将是“С о р е в н о в а н и е”和“Бл аго т в о р и т е льн о е с о р е в н о в а н и е”,分别在两个Cell1Model示例中
而且这些行已经在Switch中签入了,就像之前一样
(in无论如何,图像的实现是需要的)在xcode中有一个用于单词变格的本地化工具,也许它会对你有帮助。

相关问题