How do I create a 1px line in Interface Builder?

2019-01-13 00:19发布

Note, I'm looking to make a 1px line, not a 1pt line. Meaning it should be 1px regardless of screen scale (so 0.5pt on Retina devices).

I can do this programmatically, but can I do it in the Interface Builder? For example I cannot set a UIView to have a height of less than 1.

If I can do it in IB then I don't have to declare an outlet and manually set the frame in awakeFromNib.

10条回答
疯言疯语
2楼-- · 2019-01-13 00:50

With xCode 6 and introduction of @IBInspectable and @IBDesignable keywords it is definitely possible and rather simple. No need to subclass/outlet anything.

You can do an extension (category) for NSLayoutConstraint with following code (swift):

extension NSLayoutConstraint {

    @IBInspectable var preciseConstant: Int {
        get {
            return Int(constant * UIScreen.mainScreen().scale)
        }
        set {
            constant = CGFloat(newValue) / UIScreen.mainScreen().scale
        }
    }
}

Then you can choose needed constraint in your IB.

IB objects navigator part

Go to it's properties and set the value.

IB properties of NSLayoutConstraint

In above case it will render a view with 1 px height on 1x, 2x and 3x devices.

查看更多
Anthone
3楼-- · 2019-01-13 00:50

You can do it in .xib file. Just edit it as text and set constant="0.5" instead of "1" in your view height constraint

<constraints>
<constraint firstAttribute="height" constant="0.5" id="xUN-dm-ggj"/>
</constraints>

In Interface Builder

查看更多
ら.Afraid
4楼-- · 2019-01-13 00:55

Seems that it is not possible, one must do it programmatically or build a custom view.

查看更多
女痞
5楼-- · 2019-01-13 00:56

Based on @Nevs12 's answer and it's comments, I think it makes more sense to use such thing:

extension NSLayoutConstraint {
    @IBInspectable var usePixels: Bool {
        get {
            return false // default Value
        }
        set {
            if newValue {
                constant = constant / UIScreen.mainScreen().scale
            }
        }
    }
}
查看更多
登录 后发表回答