You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift iOS中如何按条件截断UILabel内尺寸字符串的中间部分?

处理尺寸字符串显示逻辑的Swift实现

实现步骤

  1. 拆分原始字符串:分离前缀(比如"AU")和后续的尺寸列表内容。
  2. 整理尺寸数组:将尺寸字符串分割为独立元素,清理掉多余空格。
  3. 按数量生成目标格式:
    • 尺寸数量≤8:直接拼接所有尺寸,格式化为「前缀 尺寸1, 尺寸2, ..., 尺寸N」
    • 尺寸数量>8:取前6个尺寸,加省略号后拼接最后一个尺寸,格式化为「前缀 尺寸1, 尺寸2, ..., 最后一个尺寸」

完整代码示例

func formatSizeString(_ originalString: String) -> String {
    // 拆分前缀与尺寸部分
    let components = originalString.components(separatedBy: " ")
    guard components.count >= 2 else { return originalString }
    let prefix = components[0]
    
    // 清理尺寸字符串并转为数组
    let sizeContent = components[1...]
        .joined(separator: " ")
        .replacingOccurrences(of: " ", with: "")
    let sizes = sizeContent.components(separatedBy: ",")
        .filter { !$0.isEmpty }
    
    // 根据尺寸数量处理显示逻辑
    switch sizes.count {
    case 0...8:
        let formattedSizes = sizes.joined(separator: ", ")
        return "\(prefix) \(formattedSizes)"
    default:
        let firstSix = sizes[0..<6].joined(separator: ", ")
        let lastSize = sizes.last!
        return "\(prefix) \(firstSix) ... \(lastSize)"
    }
}

// 测试用例
let testCase1 = "AU 6,7,8,9,10,11,12,13"
print(formatSizeString(testCase1)) // 输出:AU 6, 7, 8, 9, 10, 11, 12, 13

let testCase2 = "AU 6,7,8,9,10,11,...,20,21,22,23,24,25"
print(formatSizeString(testCase2)) // 输出:AU 6, 7, 8, 9, 10, 11 ... 25

let testCase3 = "US 2,3,4,5,6,7,8,9,10,11,12"
print(formatSizeString(testCase3)) // 输出:US 2, 3, 4, 5, 6, 7 ... 12

代码说明

  • 兼容前缀后带空格的情况,确保拆分逻辑稳定
  • 自动过滤尺寸数组中的空元素,避免格式错误
  • 通过switch分支清晰区分两种显示场景,新手易理解

内容的提问来源于stack exchange,提问作者Dimpy-iRoid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 12:44:55