如何设置标签背景图片比例以适应Swift?
How to set the label background image scale to fit in Swift?
我有一个用于显示某些消息的标签。我创建了一个图像,我想将其设置为我的标签背景。以下是我的做法:
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)
我想让背景图片拉伸并填满整个标签,而不是重复。知道我该怎么做吗?
如果您希望该图像应该被拉伸以填充标签宽度。试试这个代码。
challengeCell.message.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
您不能为此使用图案颜色。使用 UIImageView
显示背景图像。将 属性 添加到您的自定义单元格 class 以保存对图像视图的引用:
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")
我有一个用于显示某些消息的标签。我创建了一个图像,我想将其设置为我的标签背景。以下是我的做法:
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)
我想让背景图片拉伸并填满整个标签,而不是重复。知道我该怎么做吗?
如果您希望该图像应该被拉伸以填充标签宽度。试试这个代码。
challengeCell.message.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
您不能为此使用图案颜色。使用 UIImageView
显示背景图像。将 属性 添加到您的自定义单元格 class 以保存对图像视图的引用:
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")