Reputation: 3293
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
}
}
Upvotes: 3
Views: 4368
Reputation: 318824
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.
Upvotes: 8
Reputation: 1809
You can tell you cell to not follow the margins of the tableView this way:
cell.preservesSuperviewLayoutMargins = false
And set the margins of your cell this way:
cell.layoutMargins = UIEdgeInsets(top: 0, left: 25, bottom: 0, right: 25)
Upvotes: 0