【发布时间】:2019-08-24 23:54:26
【问题描述】:
创建了一个自定义 UIView 'MyLabelView',其中包含两个元素,1x UILabel,1x UIView,将设置为背景颜色。
MyLabelView
视图:
代码:
import UIKit
@IBDesignable
class MyLabelView: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var imageView: UIView!
@IBOutlet weak var titleLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
commonInit()
contentView?.prepareForInterfaceBuilder()
}
private func commonInit() {
let bundle = Bundle(for: type(of: self))
bundle.loadNibNamed(String(describing: type(of: self)), owner: self, options: nil)
addSubview(contentView)
}
}
我在两次使用 MyLabelView:
- MasterViewController(带有动态原型的 TableViewController)
- DetailViewController(带有静态单元格和分组样式的 TableViewController)
MasterViewController
正确显示 MyLabelView 作为自定义 UITableViewCell 的一部分
View:
代码(在 cellForRowAt 中):
let cell: MyTableViewCell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCell") as! MyTableViewCell
cell.myLabelView.titleLabel.text = "Label"
cell.myLabelView.imageView.backgroundColor = UIColor.red
// Dynamic width to fit label texts of various sizes
var frm: CGRect = cell.myLabelView.titleLabel.frame
frm.size.width = cell.myLabelView.titleLabel.intrinsicContentSize.width
cell.myLabelView.titleLabel.frame = frm
DetailViewController
在这里,我想渲染 MyLabelView 增加字体大小(工作)和右对齐,这样无论标签文本有多长,它总是与人字形对齐
View:
@987654323 @
代码(在 viewDidLoad 中):
myLabelView.titleLabel.text = "Label"
myLabelView.titleLabel.font = myLabelView.titleLabel.font.withSize(17)
myLabelView.imageView.backgroundColor = UIColor.red
// Dynamic width to fit label texts of various sizes
var frm: CGRect = myLabelView.titleLabel.frame
frm.size.width = myLabelView.titleLabel.intrinsicContentSize.width
myLabelView.titleLabel.frame = frm
预期结果
查看:
查看:
我尝试使用额外的外部 UIViews 作为容器并使用 AutoLayout,但不知何故它从来没有像我预期的那样工作。非常感谢您的帮助。
Swift 4、iOS11
更新
我试图在 IB 中设置约束,因为我无法访问单元格(使用静态单元格)。
内容视图:
标题:
MyLabelView:
【问题讨论】:
-
您能否分享包含您的自定义标签的表格视图单元格的代码或自动布局约束?可能有一种不同的方法可以在单元格中包含您的自定义标签。
标签: ios swift uitableview uiview alignment