Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make view round after autolayout

I have a tableview with custom cells which are built from storyboard with an identifier using AutoLayout.

One of the subviews needs to be round (layer.cornerRadius = width/2), it is a square in the beginning.

I have tried in layoutSubviews() but it seems to be called before AutoLayout changes its size... same thing for didMoveToSuperview()

Where is the proper function to update things like this to my subviews after AutoLayout has changed their sizes?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell_small") as! Cell
    ...
    return cell
}

// In Cell

override func layoutSubviews() {
    rankLabel.layer.cornerRadius = rankLabel.bounds.width/2
    rankLabel.layer.masksToBounds = true
}

override func didMoveToSuperview() {
    rankLabel.layer.cornerRadius = rankLabel.bounds.width/2
    rankLabel.layer.masksToBounds = true
}

Result:

like image 828
Arbitur Avatar asked May 20 '15 11:05

Arbitur


2 Answers

What I ended up doing was making a class called RoundView

class RoundView:UIView {
    override func layoutSubviews() {
        super.layoutSubviews()

        self.layer.cornerRadius = self.bounds.width/2
        self.layer.masksToBounds = true
    }
}

And then I apply it to every view I need to be round. So in Storyboard I add RoundView to Custom Class.

What was happening was that if you look inside the source of the storyboard (XML) every view had the size of the whole screen, you can look inside your own SB code. So by trying to add a corner radius equal to the width/2 inside its parent layoutSubviews() that subview hasn't got its frame set correctly. So the corner radius got the value of 320/2 instead of 50/2, thats why it got misshaped.

like image 101
Arbitur Avatar answered Sep 20 '22 15:09

Arbitur


1.Create a custom class of UIView/category

#import <UIKit/UIKit.h>
@interface RoundView : UIView

@end
#import "RoundView.h"

2.Add layoutSubviews method and set corner radius.

@implementation RoundView

-(void)layoutSubviews{

[super layoutSubviews];

self.layer.cornerRadius = self.bounds.size.width/2;

self.layer.masksToBounds = true;

}

3.Make your UIView as a subclass of RoundView and run the application, you can see circle view.

like image 40
Anisha V Avatar answered Sep 18 '22 15:09

Anisha V