我正在嘗試在@IBDesignable UIView上添加漸變。在模擬器中一切都很好,但是當我在物理設備上運行它時,漸變不會填滿屏幕。我有我的梯度代碼在一個UIView擴展:漸變不填充IBDesignable UIView
extension UIView {
func gradientFrom(_ colors: [UIColor]) {
let cgColors = colors.map({return $0.cgColor})
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.locations = [0.0, 1.0]
gradient.colors = cgColors
self.layer.insertSublayer(gradient, at: 0)
}
}
接下來,我UIView我的梯度爲中心的代碼:
@IBDesignable class MyCustomView: UIView {
var view = UIView()
// MARK: - IBOutlets
@IBOutlet weak var label: UILabel!
@IBOutlet weak var textView: UITextView!
fileprivate var gradientColors: [UIColor] = []
@IBInspectable var gradientColor0: UIColor = UIColor.flatWhite {
didSet {
gradientColors.remove(at: 0)
gradientColors.insert(gradientColor0, at: 0)
}
}
@IBInspectable var gradientColor1: UIColor = UIColor.flatWhiteDark {
didSet {
gradientColors.remove(at: 1)
gradientColors.insert(gradientColor1, at: 1)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
setup()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setup()
}
func setup() {
textView.scrollRangeToVisible(NSMakeRange(0, 0))
[gradientColor0, gradientColor1].forEach({gradientColors.append($0)})
view.gradientFrom(gradientColors)
label.textColor = labelFontColor
label.backgroundColor = UIColor.clear
textView.backgroundColor = UIColor.clear
textView.textColor = textViewFontColor
}
// MARK: - Nib handlers
fileprivate func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
}
fileprivate func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "AttributionView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
return view
}
public func applyBackgroundGradient() {
view.gradientFrom(gradientColors)
}
func resizeView() {
textView.sizeToFit()
textView.scrollRangeToVisible(NSMakeRange(0, 0))
}
}
在MyViewController,我添加了一個UIView,它的子類設置爲MyCustomView 。界面構建器填充,但是當我在物理設備上運行它時,MyCustomView中的漸變不會填滿整個屏幕。
我試圖運行從MyViewController
的viewDidLoad
,viewDidLayoutSubviews
,viewDidAppear
,applyBackgroundGradient
這些都不似乎把工作做好。
任何建議重新:如何解決這一問題,非常感謝。謝謝你的閱讀。
是否設置制約MyCustomView,這樣它會填滿屏幕? – vacawama
是的。我在模擬器中獲得了期望的結果。我在物理設備上遇到此問題。 – Adrian
您可以在模擬器上獲得所有設備尺寸的預期結果嗎? – vacawama