当前位置: 动力学知识库 > 问答 > 编程问答 >

swift - iOS AutoLayout working with something wrong

问题描述:

I add a UIView in UIStoryboard and bind it to a custom UIView class called testView,next, I create a UIView called circelView in textView in require init function ,then I crate two UILabel in circelView

this is my step

  1. initialization the circelView
  2. add AutoLayout to circelView
  3. create two UILabel and add them to circelView
  4. add AutoLayout to two UILabel

then I run the app, I can find the subView in current position , But I can not find the two UILabel in screen ,what happen?

this is my code :

 required init?(coder aDecoder: NSCoder) {

super.init(coder: aDecoder)

circelView = UIView()

self.addSubview(circelView)

circelView.snp_makeConstraints(closure: { (make) -> Void in

make.size.equalTo(80)

make.top.equalTo(self.snp_top)

make.right.equalTo(self.snp_right)

})

titleLabel = UILabel()

titleLabel.textColor = colorffffff

titleLabel.backgroundColor = UIColor.yellowColor()

titleLabel.font = font32

titleLabel.text = "hello"

titleLabel.numberOfLines = 1

titleLabel.backgroundColor = UIColor.yellowColor()

titleLabel.textAlignment = NSTextAlignment.Center

circelView.addSubview(titleLabel)

titleLabel.snp_makeConstraints { (make) -> Void in

make.center.equalTo(circelView.snp_center)

}

detailLabel = UILabel()

detailLabel.textColor = colorffffff

detailLabel.font = font24

detailLabel.text = "hello"

titleLabel.numberOfLines = 1

detailLabel.textAlignment = NSTextAlignment.Center

detailLabel.addSubview(titleLabel)

detailLabel.snp_makeConstraints { (make) -> Void in

make.top.equalTo(titleLabel.snp_bottom).offset(3)

make.centerX.equalTo(titleLabel.snp_centerX)

}

}

网友答案:

A few things could be causing this:

  • How big is your font? If your font is too large, and your view is too small (80x80 in this case), the text may not be rendered.

  • In Autolayout, it is optimal to have views have sizes based on their content, and not explicit (i.e. 80x80). By having your labels be pinned to their superview on all edges, you can have the size of your 'circelView' be dynamic to its content (the two labels). To maintain the 'circle' aspect of your 'circelView', you can constraint the height of your 'circelView' to be the same as its width.

At the end of the day, this needs more debugging. I advise examining the view hierarchy to see where your labels are. Check out the documentation here.

网友答案:

Your labels have 0 width and height. You don't set their frame anywhere in this code, and the constraints which apply to them relate only to their position, no size can be determined from them. You either need to Specify their frame or add constraints from which it could be determined by layouting engine.

分享给朋友:
您可能感兴趣的文章:
随机阅读: