RDSpinz RDSpinz - 1 year ago 148
iOS Question

Set UITableViewCell frame with margins in Swift

I am attempting to make a UITableViewCell with left and right margins/insets. I have made this in the past with Objective-C using the following code:

- (void)setFrame:(CGRect)frame {
frame.origin.x += 25;
frame.size.width -= 2 * 25;
[super setFrame:frame];

This code doesn't directly translate to Swift, as now I have to override the public frame variable, but placing this code in the setter of that variable has no effect. How would I get the margins to appear using this, or a similar technique in Swift?

This is the Swift that I have attempted:

private var otherFrame: CGRect = CGRectZero
override public var frame: CGRect {
get {
return otherFrame
set {
otherFrame = frame
otherFrame.origin.x += 25
otherFrame.size.width -= 2 * 25

Answer Source

The direct translation of the Objective-C code would be:

override var frame: CGRect {
    get {
        return super.frame
    set {
        var frame = newValue
        frame.origin.x += 25
        frame.size.width -= 2 * 25

        super.frame = frame

There's no need for the additional property. You use the implicit value newValue in the setter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download