Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

ios - Rounded rect using UIRectCorner in Swift not working

I am trying to create a rounded rect for the UITableViewCell I have created in a storyboard. I am using Swift 2 in Xcode 7. I have two views in the prototype cell, topView and Bottom view. I want the topView to have its top corners rounds, and the bottomView to have its corners rounded.

in awakeFromNib (may go somewhere else better later):

...
self.topView.backgroundColor = UIColor.redColor()
self.bottomView.backgroundColor = UIColor.grayColor()

self.setMaskToView(self.topView, corners:UIRectCorner.TopLeft.union(UIRectCorner.TopRight))
self.setMaskToView(self.bottomView, corners: UIRectCorner.BottomLeft.union(UIRectCorner.BottomRight))
...

In separate function (based on an answer to another Stack overflow post):

func setMaskToView(view : UIView, corners: UIRectCorner) {
    let rounded = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: 10, height: 10))
    let mask = CAShapeLayer()

    mask.path = rounded.CGPath
    view.layer.mask = mask
}

Note, I also tried [.TopRight, .TopLeft] instead of the union(), based on various other stack overflow posts. Nothing seems to change anything. Also cleaned and restarted Xcode in desperation. This is what I am getting:

Top Cell Shows issue.  Only .TopLeft seems to be applied, even though it is called on two separate views

If anyone has any ideas what might be up, I would appreciate it.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have two problems.

  1. awakeFromNib is too early to do anything based on view bounds, because the views haven't been resized for the device at that point. You should create the mask layers in awakeFromNib, but you should set their paths in layoutSubviews.

  2. In setMaskToView(_:corners:), you need to use view.bounds, not self.bounds, to create the path.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...