【发布时间】:2016-07-26 01:44:59
【问题描述】:
我的 UIView 像这样堆叠在一起:
每个 UIView 都在 wordContainer 内。每个 UIView 里面都有两个UILabel
我用两个子 UILabel 像这样创建每个单独的 UIView:
var labels = [UIView]()
for word in words {
let wordLabel = UILabel(frame: CGRectZero)
wordLabel.text = word.valueForKey("sanskrit") as? String
wordLabel.numberOfLines = 0
wordLabel.sizeToFit()
wordLabel.translatesAutoresizingMaskIntoConstraints = false
let englishWordLabel = UILabel(frame: CGRectMake(wordLabel.frame.width + 10,0,0,0))
englishWordLabel.text = word.valueForKey("english") as? String)
englishWordLabel.numberOfLines = 0
englishWordLabel.sizeToFit()
englishWordLabel.lineBreakMode = .ByWordWrapping
englishWordLabel.translatesAutoresizingMaskIntoConstraints = false
let wordView = UIView(frame: CGRectMake(0,0,self.view.frame.width,englishWordLabel.frame.height))
wordView.translatesAutoresizingMaskIntoConstraints = false
wordView.addSubview(wordLabel)
wordView.addSubview(englishWordLabel)
wordView.sizeToFit()
labels.append(wordView)
}
然后我把这个 UIView 的集合添加到我的wordContainer。这是我想的部分,我应该设置 NSLayoutConstraints。这个想法是我希望它们都正确地堆叠在一起。例如,它应该如下所示:
word: definition
word: definition
word: definition
word: definition
但它看起来像这样:
我将它们添加到 wordContainer 中,如下所示:
let wordContainer = UIView(frame: CGRectZero)
var currentY:CGFloat = 0.0
let margin_height:CGFloat = 4.0
var height:CGFloat = 0
for view in wordViews {
var rect = view.frame
rect.origin.y = currentY
view.frame = rect
currentY += view.frame.height
height += view.frame.height
wordContainer.addSubview(view)
}
let containRect = CGRectMake(0,0,self.view.frame.width, height)
wordContainer.frame = containRect
然后我为wordContainer 设置了我的约束条件,这实际上允许所有单词存在的空间,如果它们没有堆叠在一起的话:
wordContainer.bottomAnchor.constraintEqualToAnchor(cell.contentView.bottomAnchor).active = true
wordContainer.topAnchor.constraintEqualToAnchor(cell.contentView.topAnchor).active = true
我的最新想法是,也许我应该为此添加约束。我已经尝试将NSLayoutConstraints 添加到cell 的高度,并且当我这样做时,所有单词都不再适当地布置。相反,它们堆叠在一起。但这似乎是正确的方向..
【问题讨论】:
-
不使用自动布局就不能使用
UITableViewAutomaticDimension -
@dan by autolayout,你指的是 IB Visual 吗?
-
自动布局是指为视图添加约束。您真的应该为此使用
UIStackView,而不是尝试通过设置框架手动堆叠您的视图
标签: ios swift uitableview ios8 constraints