gpt4 book ai didi

ios - 具有自定义层的 UIButton 子类不会完全填充相邻 View 的空间

转载 作者:行者123 更新时间:2023-11-30 13:57:52 24 4
gpt4 key购买 nike

我试图创建一个带有图标的方形按钮,背景是透明的。当按钮突出显示时,背景变为白色。一切正常,但后来我注意到按钮的右侧白色边框在突出显示时并不像边框的其余部分那么清晰。经过一番研究,我意识到只有将右侧 View 设置为“将中心 X 对齐到: super View ”时才会发生这种情况。这是我制作的一个例子:

enter image description here

您看到的白色字段是我制作的矩形按钮(代码如下)。请注意,通过按钮和绿色 UIView 之间的小间隙可以看到一些红色背景色。绿色 View 设置为“Align Center X to: Superview”,按钮的尾随空格为 0 到绿色 View 。下面的蓝色 UIView 没有遇到这种奇怪的间隙。

现在看这张图片:

enter image description here

这是完全相同的设置,但现在绿色 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

最佳答案

我最终通过创建一个填充的 CAShapeLayer 并将其作为子图层添加到按钮来解决这个问题,而不是设置白色背景图像。由于某种原因,这有效。

关于ios - 具有自定义层的 UIButton 子类不会完全填充相邻 View 的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33377998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com