我有以下代码,我试图实现添加到垂直滚动视图的动态图像。我想有它的约束,所以图像设置在scrollView的边框内。
然而结果是图像似乎保持原始大小(比滚动视图大,因此图像被裁剪)
以下是代码:
@IBOutlet weak var myScrollView: UIScrollView!
private let lettersModel:LettersModel = LettersModel();
private var imgs = [UIImageView]();
override func viewDidLoad() {
super.viewDidLoad()
myScrollView.backgroundColor = UIColor.brownColor()
for var index=0; index<1; index++
{
let myImage:UIImage = UIImage(named: lettersModel.getLetterAt(index))!
let myImageView:UIImageView = UIImageView()
myImageView.image = myImage
myImageView.contentMode = UIViewContentMode.ScaleAspectFit
myScrollView.addSubview(myImageView)
myImageView.translatesAutoresizingMaskIntoConstraints = false;
myScrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[myImageView]-|", options: [], metrics: nil, views:["myImageView":myImageView] ))
imgs.append(myImageView)
}
}
答案 0 :(得分:2)
UIView
内的 UIScrollView
无法调整其父级的大小。{p> layoutSubviews
您可以在UIScrollView中创建UIView并更新UIScrollView
中的宽度,并在UIView中添加所有UIView。以下是如何执行此操作:(为此,您需要设置class MyScrollView : UIScrollView {
let contentView = UIView()
override init (frame : CGRect) {
super.init(frame : frame)
addSubview(contentView)
}
convenience init () {
self.init(frame:CGRect.zero)
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
override func layoutSubviews() {
contentView.frame.size.width = frame.width
contentView.frame.size.height = contentSize.height
super.layoutSubviews()
}
}
var myScrollView = MyScrollView(frame: CGRect(x: 0, y: 0, width: 400, height: 600))
var imgs = [UIImageView]();
let myImage = UIImage(named: "achtergrond")
let myImageView:UIImageView = UIImageView()
myImageView.image = myImage
myImageView.contentMode = UIViewContentMode.ScaleAspectFit
myScrollView.contentSize.height = 1000 // <-- setting the contentSize
myScrollView.contentView.addSubview(myImageView) // <-- You add the UIImageView to the contentView
myImageView.translatesAutoresizingMaskIntoConstraints = false;
myScrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[myImageView]-|", options: [], metrics: nil, views:["myImageView":myImageView] ))
imgs.append(myImageView)
的contentSize的高度,但您还必须设置此值以使其滚动。)
REQUEST_URI
答案 1 :(得分:1)
您必须像下面一样激活它们,只需为您的实现编辑代码。
wget