如何在Swift中更改UITableView Cell文本宽度

时间:2015-08-14 08:27:39

标签: ios uitableview cell

我正在尝试更改UITableview

中单元格文本的宽度

enter image description here

我正在看容器的宽度

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

我想展示像(截断尾巴):

enter image description here

3 个答案:

答案 0 :(得分:4)

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

cell.textLabel?.adjustsFontSizeToFitWidth = true;

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

 cell.textLabel?.numberOfLines = 0

它使Label文本显示为两行。

修改

如果你想为textLabel截断tail,试试这个。

cell.textLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail

答案 1 :(得分:1)

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

答案 2 :(得分:0)

实际上,在TableView中不允许更改单元格中textLabel的框架。每个单元格的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框架的效果。