Adding padding to an UIView

后端 未结 7 1307
长情又很酷
长情又很酷 2020-12-23 12:55

I\'m looking for a way to add a padding property to an UIView. Ideally, I would like to avoid subclassing and putting it in a category. The usage would be somet

相关标签:
7条回答
  • 2020-12-23 13:35

    You can override the alignmentRectInsets property. Here is an example in Swift 4

    class YourCustomView: UIView {
    
        override var alignmentRectInsets: UIEdgeInsets {
            return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        }
    }
    
    0 讨论(0)
  • 2020-12-23 13:38

    You can inset the view's frame/bounds like this:

        yourView.frame = yourView.frame.inset(by: UIEdgeInsets(top: .zero, left: 5.0, bottom: 5.0, right: .zero)
    
    0 讨论(0)
  • 2020-12-23 13:47

    Update for Swift 4:

    self.yourView.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
    
    0 讨论(0)
  • 2020-12-23 13:49

    Update for Swift 3

    view.bounds = view.frame.insetBy(dx: 10.0, dy: 10.0)
    

    :)

    0 讨论(0)
  • 2020-12-23 13:49

    Update: Since iOS11 you should use directionalLayoutMargins instead of layoutMargins.

    Source: https://developer.apple.com/documentation/uikit/uiview/1622566-layoutmargins?language=objc

    Since iOS 8, each view has now a layoutMargins property which corresponds to the padding.

    myview.layoutMargins = UIEdgeInsetsMake(10, 10, 10, 10);
    

    When you use AutoLayout, a format with |-[subview]-|, |- will refer to the edges defined with layoutMargins.

    Source: https://developer.apple.com/reference/uikit/uiview/1622566-layoutmargins?language=objc

    0 讨论(0)
  • 2020-12-23 13:53

    What you really have to do is create a view and add a subview to it. Make one view the background and give it the frame you want. Then make the second subview the frame you want with the edge insets.

    UIView backgroundView = new UIView(CGRect.FromLTRB(0, 0, 100, 100))
    {
        BackgroundColor = backgroundGray,
    };
    
    //Will have a right edge inset of 10
    UIView edgyView = new UIView(CGRect.FromLTRB(0, 0, 90, 100))
    {
        BackgroundColor = backgroundGray,
    }
    
    backgroundView.AddSubview(edgyView);
    
    0 讨论(0)
提交回复
热议问题