,而不是試圖直接編碼幀值,我建議你採用自動佈局。這是一個UIView子類的基礎,它可以做你想做的事(我沒有爲字體打擾,但你可以很容易地添加它) -
import UIKit
@IBDesignable
class MyView: UIView {
var headerLabel:UILabel!
var bodyLabel:UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
self.addLabels()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addLabels()
}
func addLabels() {
self.translatesAutoresizingMaskIntoConstraints=false
self.headerLabel=UILabel()
self.headerLabel.translatesAutoresizingMaskIntoConstraints=false
self.headerLabel.textAlignment=NSTextAlignment.Center
self.addSubview(self.headerLabel)
self.bodyLabel=UILabel()
self.bodyLabel.translatesAutoresizingMaskIntoConstraints=false
self.bodyLabel.numberOfLines=0
self.bodyLabel.textAlignment=NSTextAlignment.Center
self.addSubview(self.bodyLabel)
}
override func updateConstraints() {
self.addConstraint(NSLayoutConstraint(item: self.headerLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 24))
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.headerLabel, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.bodyLabel, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.bodyLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 24))
self.addConstraint(NSLayoutConstraint(item: self.bodyLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.headerLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 12))
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.LeadingMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.bodyLabel, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.bodyLabel, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0))
super.updateConstraints()
}
override func prepareForInterfaceBuilder() {
self.headerLabel.text="Header"
self.bodyLabel.text="Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum "
}
}
你應該使用約束而不是絕對幀。如果您使用這樣的框架,您的輸出將無法適應不同的設備顯示屏尺寸 – Paulw11
您是否可以在代碼中提供幫助?我正在複製用戶界面以顯示在Carouself ScrollView中@ Paulw11 –