如何在UITabel内部的UILabel中设置背景图像

时间:2017-08-20 06:33:28

标签: ios swift uitableview swift3 uiimageview

我正在研究swift 3中的一个项目,我在UILabel内部设置了一个UITableViewCell内的背景图像。图像由渐变颜色组成,其边缘具有淡化效果。一旦我因为某些原因在我的代码中设置了这个,渐变颜色似乎只出现在标签的一侧(左侧)。也许它没有经过适当调整以适应UILabel。如何将图像设置为适当的标签大小,帮助将非常感激。我的代码如下:我错过了什么

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    switch indexPath.row {
    case 0:
        let cell =  tableView.dequeueReusableCell(withIdentifier: "FeaturedCell", for: indexPath)
        cell.bounds = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: cell.bounds.height)
        return cell

    case (1...3):

        let text = self.categorySelectionTitles[indexPath.row  - 2]
        let cell = tableView.dequeueReusableCell(withIdentifier: "AudioCell",for: indexPath)
        let labe = cell.viewWithTag(TABLE_CELL_TAGS.headerLabel) as! UILabel
        labe.backgroundColor = UIColor(patternImage: UIImage(named: "headerBar")!)
         labe.bounds = CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height)
        Utils.setTableCellLabelText(cell: cell, labelTag: 501, text: text)
        return cell

}

enter image description here

如上图所示,渐变的右侧不存在。下面的图片如下所示。

enter image description here

1 个答案:

答案 0 :(得分:1)

你可以使用autolayout而不是像这样的帧:

labe.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
  labe.leftAnchor.constraint(equalTo: cell.leftAnchor),
  labe.rightAnchor.constraint(equalTo: cell.rightAnchor),
  labe.topAnchor.constraint(equalTo: cell.topAnchor),
  labe.bottomAnchor.constraint(equalTo: cell.bottomAnchor),
])

您希望尝试确保仅添加约束一次。

或使用面具:

labe.autoresizingMask = [.flexibleWidth, .flexibleHeight]
相关问题