iOS: frame.size.width/2 doesn't produce a circle on every device

后端 未结 6 1421
长发绾君心
长发绾君心 2020-11-29 06:09

I\'m aware that the formulae frame.size.width/2 should produce a circle border, however in XCode I am currently experiencing some discrepancies.

I have

6条回答
  •  既然无缘
    2020-11-29 06:57

    If you test in iOS8.3, you should call layoutIfNeed on your UI object before get its frame. Please read iOS8.3 Release notes

    For example:

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    // code that sets up the button, but doesn’t yet add it to a window
    CGRect titleFrame = button.titleLabel.frame;
    // code that relies on the correct value for titleFrame
    

    You now need:

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    // code that sets up the button, but doesn’t yet add it to a window
    [button layoutIfNeeded]; // This is also safe pre-iOS 8.3
    CGRect titleFrame = button.titleLabel.frame;
    // code that relies on the correct value for titleFrame
    

    It's said that for UIButton and sub-classes but you can try it also with your UI object.

    When linking against iOS 8.3, any code that relies on layout information (such as the frame) of a UIButton subview when the button is not in the window hierarchy will need to send layoutIfNeeded to the button before retrieving layout information (such as button.titleLabel.frame) to ensure that the layout values are up to date.

    Also, as the imgAvatar's cornerRadius was set to 1/2 of imgFrame's size, you will get a circle only if that cornerRadius value = 1/2 of imgAvatar's width (and height).

    So, after the call:

    imgAvatar.layer.cornerRadius = imgFrame.frame.size.width/2
    

    verify :

    • frame size of imgAvatar and its cornerRadius
    • be sure that image is squared

提交回复
热议问题