0
請在下面找到我的代碼使用自動版式佈局一個UITableViewCell的UI編程:斯威夫特4 - 在自動版式的UITableViewCell切碎多行標籤編程
// Profile Pic
profileView.translatesAutoresizingMaskIntoConstraints = false
profileView.widthAnchor.constraint(equalToConstant: commentImageSize + 4).isActive = true
profileView.heightAnchor.constraint(equalToConstant: commentImageSize + 4).isActive = true
profileView.topAnchor.constraint(equalTo: topAnchor, constant: borderSize).isActive = true
profileView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: borderSize).isActive = true
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.widthAnchor.constraint(equalToConstant: commentImageSize).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: commentImageSize).isActive = true
profileImageView.topAnchor.constraint(equalTo: profileView.topAnchor, constant: 2).isActive = true
profileImageView.leadingAnchor.constraint(equalTo: profileView.leadingAnchor, constant: 2).isActive = true
// Time Ago Label
timeAgoLabel.translatesAutoresizingMaskIntoConstraints = false
timeAgoLabel.topAnchor.constraint(equalTo: usernameLabel.topAnchor).isActive = true
timeAgoLabel.leadingAnchor.constraint(equalTo: usernameLabel.trailingAnchor, constant: 0)
timeAgoLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -borderSize).isActive = true
// Username Label
usernameLabel.translatesAutoresizingMaskIntoConstraints = false
usernameLabel.leadingAnchor.constraint(equalTo: profileView.trailingAnchor, constant: borderSize).isActive = true
usernameLabel.trailingAnchor.constraint(equalTo: timeAgoLabel.leadingAnchor, constant: -borderSize).isActive = true
// *****
// (Not work)
// usernameLabel.topAnchor.constraint(equalTo: profileView.topAnchor).isActive = true
// (Work)
usernameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: borderSize).isActive = true
// *****
// Comment Label
commentLabel.translatesAutoresizingMaskIntoConstraints = false
commentLabel.leadingAnchor.constraint(equalTo: usernameLabel.leadingAnchor).isActive = true
commentLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -borderSize).isActive = true
commentLabel.topAnchor.constraint(equalTo: usernameLabel.bottomAnchor, constant: 2).isActive = true
commentLabel.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -borderSize).isActive = true
在實現我的目標之前,我嘗試了另一個實現。具體的實現是以下幾點:
usernameLabel.topAnchor.constraint(equalTo: profileView.topAnchor).isActive = true
後,我用下面的代碼,一切完美地工作:
usernameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: borderSize).isActive = true
碼的兩條線應該有我的期望相同的效果。我想知道爲什麼我原來的暗示不能按預期工作。
謝謝。
因爲我對'profileView'約束已經超過其頂層的頂部,如果我將'usernameLabel'頂部對齊到'profileView'的頂部,它不應該暗示有' usernameLabel'頂部,爲多行標籤提供頂部限制? – Wilfred
你是對的,如果所有的垂直約束條件都是連接的,並且暗示他們推動了超視圖的頂部和底部,那麼多行標籤應該正確放置在那裏。但是,使用'lessThanOrEqualTo'或'greaterThanOrEqualTo'可能無濟於事,只需用'equalTo'來替換它。 – Glenn