【发布时间】:2026-02-02 02:25:01
【问题描述】:
我试图创建一个带有图标的方形按钮,其中背景是透明的。当按钮突出显示时,背景变为白色。一切正常,但后来我注意到按钮的右侧白色边框在突出显示时不如边框的其余部分清晰。经过一些研究,我意识到只有当右侧的视图设置为“将 X 中心对齐到:Superview”时才会发生这种情况。这是我做的一个例子:
您看到的白色区域是我制作的矩形按钮(代码如下)。请注意,通过按钮和绿色 UIView 之间的小间隙可以看到一些红色背景颜色。绿色视图设置为“Align Center X to: Superview”,并且按钮的尾随空间为 0 到绿色视图。下面蓝色的 UIView 没有遇到这种奇怪的差距。
现在看这张图:
这是完全相同的设置,但现在绿色 UIView 具有“Trailing Space to: Superview = 140”而不是 X 居中。现在差距消失了!为什么会这样?
这是绘制白色按钮的代码。
import UIKit
@IBDesignable
class SquareButton: UIButton {
var iconLayer: CAShapeLayer!
func setup() {
if iconLayer == nil {
iconLayer = CAShapeLayer()
// Create a custom white background color
let rect = CGRectMake(0.0, 0.0, self.bounds.width, self.bounds.height)
UIGraphicsBeginImageContext(self.bounds.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
// Set forState .Normal just for this example
self.setBackgroundImage(image, forState: .Normal)
}
}
override func layoutSubviews() {
super.layoutSubviews()
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
任何帮助将不胜感激! :D
【问题讨论】:
标签: ios swift uibutton autolayout