ios – 自动布局后使视图回合

前端之家收集整理的这篇文章主要介绍了ios – 自动布局后使视图回合前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个自定义单元格的tableview,它是使用AutoLayout从带有标识符的storyboard构建的.

其中一个子视图需要是圆形的(layer.cornerRadius = width / 2),它在开头是一个正方形.

我在layoutSubviews()中尝试过,但似乎在AutoLayout改变其大小之前调用…同样的事情为didMoveToSuperview()

在AutoLayout更改其大小后,将此类内容更新到我的子视图的正确功能在哪里?

  1. func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  2. let cell = tableView.dequeueReusableCellWithIdentifier("cell_small") as! Cell
  3. ...
  4. return cell
  5. }
  6.  
  7. // In Cell
  8.  
  9. override func layoutSubviews() {
  10. rankLabel.layer.cornerRadius = rankLabel.bounds.width/2
  11. rankLabel.layer.masksToBounds = true
  12. }
  13.  
  14. override func didMoveToSuperview() {
  15. rankLabel.layer.cornerRadius = rankLabel.bounds.width/2
  16. rankLabel.layer.masksToBounds = true
  17. }

结果:

解决方法

我最终做的是创建一个名为RoundView的类
  1. class RoundView:UIView {
  2. override func layoutSubviews() {
  3. super.layoutSubviews()
  4.  
  5. self.layer.cornerRadius = self.bounds.width/2
  6. self.layer.masksToBounds = true
  7. }
  8. }

然后我将它应用于我需要绕过的每个视图.所以在Storyboard中我将RoundView添加到Custom Class.

发生的事情是,如果您查看故事板(XML)的源代码,每个视图都具有整个屏幕的大小,您可以查看自己的SB代码.因此,通过尝试在其父layoutSubviews()内添加等于width / 2的角半径,子视图未正确设置其框架.所以角半径的值为320/2而不是50/2,这就是它变形的原因.

猜你在找的iOS相关文章