1
請我需要用下面的幫助,我剛開始學習如何編程的設計界面,一些教程後,我想嘗試一些東西,然後,我就stucked添加約束編程迅速
我想達到以下圖像
,但是這是我得到
這低於
class FeedsCell: UICollectionViewCell{
override init(frame: CGRect){
super.init(frame: frame)
setupViews()
}
let thumNailImageView : UIImageView = {
let imageView = UIImageView()
imageView.backgroundColor = UIColor.blue
return imageView
}()
let sourceName:UILabel = {
let srcLabel = UILabel()
srcLabel.backgroundColor = UIColor.purple
srcLabel.translatesAutoresizingMaskIntoConstraints = false
return srcLabel
}()
let separatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.black
return view
}()
func setupViews(){
addSubview(thumNailImageView)
addSubview(separatorView)
addSubview(sourceName)
addConstraintsWithFormat(format: "H:|-16-[v0(194)]", views: thumNailImageView)
addConstraintsWithFormat(format: "V:|-16-[v0]-16-[v1(1)]|", views: thumNailImageView, separatorView)
addConstraintsWithFormat(format: "H:|[v0]|", views: separatorView)
//left Constriants
addConstraint(NSLayoutConstraint(item: sourceName, attribute: .left, relatedBy: .equal, toItem: thumNailImageView, attribute: .right, multiplier: 1, constant: 8))
//Right constraints
addConstraint(NSLayoutConstraint(item: sourceName, attribute: .right, relatedBy: .equal, toItem: thumNailImageView, attribute: .right, multiplier: 1, constant: 0))
addConstraintsWithFormat(format: "H:|-8-[v0]-8-|", views: sourceName)
addConstraintsWithFormat(format: "V:|-8-[v0(20)]", views: sourceName)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension UIView{
func addConstraintsWithFormat(format: String, views: UIView...){
var viewDictionary = [String: UIView]()
for(index, view) in views.enumerated(){
let key = "v\(index)"
view.translatesAutoresizingMaskIntoConstraints = false
viewDictionary[key] = view
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewDictionary))
}
}
略OT的問題我的代碼,但你有沒有考慮過使用新的錨API?我發現做這種事情要容易得多。可能是一個簡單的錯誤(我乍一看沒有看到)會消失。例如。 'sourceName.leftAnchor.constrainEqualToAnchor(thumNailImageView.rightAnchor).isActive = true' –
@TravisGriggs一個更好的解決方案是使用xibs和故事板。 – Sulthan
@Sulthan我可以使用xibs和storyboard來實現它,但我試圖以編程方式做到這一點,因爲我將執行一些功能 – SimpiMind