我有UIView子类,并且为了布局UI元素,我没有使用自动布局。我想设置框架取决于框架的宽度或高度。但是,当我在alloc]init]
方法之后立即执行此操作时,它看起来像self.frame.size.height或width为零。对于临时解决方案,我做了以下:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.25 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
UIImage *img = [UIImage imageNamed:@"sound_level_arrow"];
_arrowImgView = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width/2, 0, img.size.width, img.size.height)];
_arrowImgView.center = CGPointMake(self.mainImgView.frame.size.width/2, self.mainImgView.frame.size.height-2);
_arrowImgView.image = [UIImage imageNamed:@"sound_level_arrow"];
_arrowImgView.contentMode = UIViewContentModeCenter;
[self.mainImgView addSubview:_arrowImgView];
});
但当然我需要知道,当视图完成加载并且它具有实际的self.frame.size.width和height。
答案 0 :(得分:7)
如果要在自定义视图子类中执行此操作,请覆盖该类中的layoutSubviews
。由于iOS可能会多次发送layoutSubviews
,因此请务必仅在第一时间创建_arrowImgView
:
- (void)layoutSubviews {
[super layoutSubviews];
if (_arrowImgView == nil) {
UIImage *image = [UIImage imageNamed:@"sound_level_arrow"];
_arrowImgView = [[UIImageView alloc] initWithImage:image];
_arrowImgView.contentMode = UIViewContentModeCenter;
[self addSubview:_arrowImgView];
}
CGRect myBounds = self.bounds;
CGRect mainFrame = self.mainImageView.frame;
_arrowImgView.bounds = CGRectMake(0, 0, myBounds.size.width, myBounds.size.height);
_arrowImgView.center = CGPointMake(mainFrame.size.width / 2, mainFrame.size.height - 2);
}
答案 1 :(得分:2)
使用这个。它处理方向更改和重绘渐变背景。
import UIKit
@IBDesignable
final class GradientButton: UIButton {
@IBInspectable var startColor: UIColor = UIColor.clear
@IBInspectable var endColor: UIColor = UIColor.clear
override func draw(_ rect: CGRect) {
if let gradient = layer.sublayers?.first as? CAGradientLayer {
gradient.removeFromSuperlayer()
}
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = CGRect(origin: CGPoint.zero, size: self.frame.size)
gradient.colors = [startColor.cgColor, endColor.cgColor]
layer.insertSublayer(gradient, at: 0)
super.draw(rect)
}
@IBInspectable var imageContentMode: Int {
get {
return imageView?.contentMode.rawValue ?? 0
}
set {
imageView?.contentMode = UIViewContentMode(rawValue: newValue) ?? .scaleAspectFit
}
}
}
答案 2 :(得分:-4)
viewWillLayoutSubviews和最后一个viewDidLayoutSubviews
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
// your code for positioning any subview here
}