在 Swift 中设置带有边距的 UITableViewCell 框架 [英] Set UITableViewCell frame with margins in Swift

查看:48
本文介绍了在 Swift 中设置带有边距的 UITableViewCell 框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个带有左右边距/插图的 UITableViewCell.我过去曾使用以下代码通过 Objective-C 完成此操作:

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];
}

这段代码不会直接转换为 Swift,因为现在我必须覆盖公共框架变量,但是将这段代码放在该变量的 setter 中没有任何效果.我将如何使用此方法或 Swift 中的类似技术来显示边距?

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?

这是我尝试过的 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
    }
}

推荐答案

Objective-C 代码的直接翻译是:

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
    }
}

不需要额外的属性.您在 setter 中使用隐式值 newValue.

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

这篇关于在 Swift 中设置带有边距的 UITableViewCell 框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆