我有一个用于显示某些消息的标签。我创建了一个图像,希望将其设置为标签背景。以下是我的操作方式:
challengeCell.message.text = " You have taken \(historyArray[indexPath.row]) in this week"
challengeCell.message.backgroundColor = UIColor(patternImage: UIImage(named: "challengeMessage")!)
//this is a suggested attempt
challengeCell.message.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
我想拉伸背景图像并填充整个标签,而不要重复。知道我该怎么做吗?
答案 0 :(得分:0)
如果您希望该图像拉伸以填充标签宽度。试试这个代码。
challengeCell.message.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
答案 1 :(得分:0)
您不能为此使用图案颜色。使用UIImageView
显示背景图像。在自定义单元格类中添加一个属性,以保留对图像视图的引用:
class ChallengeCell: UITableViewCell {
let messageBackgroundView = UIImageView()
override func layoutSubviews() {
if messageBackgroundView.superview != message.superview {
message.superview.insertSubview(messageBackgroundView, belowSubview: message)
messageBackgroundView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
messageBackgroundView.leadingAnchor.constraint(equalTo: message.leadingAnchor),
messageBackgroundView.trailingAnchor.constraint(equalTo: message.trailingAnchor),
messageBackgroundView.topAnchor.constraint(equalTo: message.topAnchor),
messageBackgroundView.bottomAnchor.constraint(equalTo: message.bottomAnchor),
])
messageBackgroundView.contentMode = .scaleToFill
}
super.layoutSubviews()
}
...
}
要设置消息背景时,请设置图像视图的图像:
challengeCell.messageBackgroundView.image = UIImage(named: "challengeMessage")