【发布时间】:2019-04-04 12:11:40
【问题描述】:
我正在尝试在不使用情节提要的情况下在 Swift for iOS 中制作登录注册 UI。
在我的控制器中使用此代码:
loginButton.translatesAutoresizingMaskIntoConstraints = false
loginButton.layer.borderWidth = 1
loginButton.clipsToBounds = true
loginButton.layer.borderColor = UIColor.Palette.boldYellow.cgColor
loginButton.setTitle("Login", for: .normal)
loginButton.setTitleColor(UIColor.Palette.boldYellow, for: .normal)
loginButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 24)
loginButton.heightAnchor.constraint(equalToConstant: 58).isActive = true
NSLayoutConstraint(item: loginButton, attribute: .leading, relatedBy: .equal, toItem: footerView, attribute: .leading, multiplier: 1, constant: 30).isActive = true
NSLayoutConstraint(item: loginButton, attribute: .trailing, relatedBy: .equal, toItem: footerView, attribute: .trailing, multiplier: 1, constant: -30).isActive = true
NSLayoutConstraint(item: loginButton, attribute: .top, relatedBy: .equal, toItem: footerView, attribute: .top, multiplier: 1, constant: 21).isActive = true
registerButton.translatesAutoresizingMaskIntoConstraints = false
registerButton.clipsToBounds = true
registerButton.setTitle("Register", for: .normal)
registerButton.setTitleColor(.white, for: .normal)
registerButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 24)
registerButton.heightAnchor.constraint(equalToConstant: 58).isActive = true
NSLayoutConstraint(item: registerButton, attribute: .leading, relatedBy: .equal, toItem: footerView, attribute: .leading, multiplier: 1, constant: 30).isActive = true
NSLayoutConstraint(item: registerButton, attribute: .trailing, relatedBy: .equal, toItem: footerView, attribute: .trailing, multiplier: 1, constant: -30).isActive = true
NSLayoutConstraint(item: registerButton, attribute: .bottom, relatedBy: .equal, toItem: footerView, attribute: .bottom, multiplier: 1, constant: -21).isActive = true
我可以做到:
但我想让“注册”文本加粗,所以我添加了这一行:
registerButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 24)
就在之前
registerButton.heightAnchor.constraint(equalToConstant: 58).isActive = true
但是,整个界面都坏了,我得到了这个:
看起来我对两个按钮的图层所做的更改都没有应用。
我在控制器的 viewDidLayoutSubviews 覆盖中进行这些层更改:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let gradientBackgroundButton = CAGradientLayer()
gradientBackgroundButton.frame = registerButton.bounds
gradientBackgroundButton.startPoint = CGPoint.zero
gradientBackgroundButton.endPoint = CGPoint(x: 1, y: 1)
gradientBackgroundButton.colors = [UIColor.Palette.lightYellow.cgColor, UIColor.Palette.boldYellow.cgColor]
registerButton.layer.insertSublayer(gradientBackgroundButton, at: 0)
registerButton.layer.cornerRadius = registerButton.bounds.height / 2
loginButton.layer.cornerRadius = loginButton.bounds.height / 2
}
我的猜测是,当我不指定字体大小时,我的视图需要调用 viewDidLayoutSubviews 而不是在我指定字体大小时。在这种情况下,我应该在哪里修改按钮的图层?
【问题讨论】:
-
这段代码在我的模拟器上运行良好,我只是固定了页脚的高度。
-
是的,当您通过设置 view.bounds.height 属性为视图提供固定大小时,它工作正常,但我想使用约束来保持 UI 尽可能响应。 @VDPurohit
标签: ios swift uibutton autolayout uikit