繁体   English   中英

如何在 Swift 中更改 UITableView 单元格文本宽度

[英]How to change UITableView Cell text width in Swift

我正在尝试更改 UITableview 中单元格文本的宽度

在此处输入图片说明

正如我所看到的,它占用了容器的宽度

var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = users[indexPath.row].User
    cell.detailTextLabel?.text=String(users[indexPath.row].Score)
   
    cell.textLabel?.bounds.width=20

我想展示类似(截尾)的东西:

在此处输入图片说明

我认为 screen short 似乎你已经达到了屏幕宽度。所以增加标签宽度没有用。如果你想显示你的 textLabel 的全文,你可以遵循以下任何一种解决方案。

cell.textLabel?.adjustsFontSizeToFitWidth = true;

它根据标签宽度调整字体大小。

 cell.textLabel?.numberOfLines = 0

它使标签文本显示为两行。

编辑

如果你想截断 textLabel 的尾部,试试这个。

cell.textLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail

如果您使用自动布局,您可以将右侧的数字固定到容器视图的右边缘,放置一个水平间隔并为名称标签提供比数字标签更低的压缩阻力优先级。 这将使名称标签尽可能宽,但不会太宽以至于它会夹在数字中。

实际上,TableView 中不允许更改单元格中 textLabel 的框架。 每个单元格的文本标签的框架宽度与单元格相关,开发人员无法通过编程方式设置它。 不过,我想出了一个可行的解决方案:我们可以不改变textLabel的框架,但我们可以交替改变源文本。 如果我们能提前截断源字符串,这个问题就迎刃而解了。

//Assign each element in the array a row in table view

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var myCell = myTableView.dequeueReusableCell(withIdentifier: "The Cell")

    if myCell == nil {
        myCell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "The Cell")
    }

    myCell?.accessoryType = UITableViewCellAccessoryType.none

    // If the text is too long (longer than 20 char), the text will be truncated
    // The lenght of label cannot be set effectively here, so I truncate the source string alternatively
    var myString: String = sectionArray[indexPath.section].items[indexPath.row]
    if myString.characters.count > 20 {

        let myIndex = myString.index(myString.startIndex, offsetBy: 20)
        myString = myString.substring(to: myIndex)
        myString += "..."
    }

    myCell?.textLabel?.text = myString
    myCell?.detailTextLabel?.text = "\(NSDate())"

    return myCell!
}

通过这个方法,可以达到改变textLabel的frame的效果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM