我正在使用 UIViewRepresentable 结构在 SwiftUI 中嵌入“使用 Apple 登录”按钮来显示按钮。
import SwiftUI
import UIKit
import AuthenticationServices
final class AppleIDButton: UIViewRepresentable {
typealias UIViewType = UIView
var appleButton = ASAuthorizationAppleIDButton()
func makeUIView(context: UIViewRepresentableContext<AppleIDButton>) -> UIView {
let view = UIView()
view.addSubview(appleButton)
return view
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<AppleIDButton>) {
appleButton.cornerRadius = 8
}
}
...//这是我的 SwiftUI 文件中的代码
ZStack(alignment: .top) {
VStack(spacing: 0) {
Rectangle()
.frame(width: screenWidth, height: 1)
.foregroundColor(Color("lineGray"))
Rectangle()
.frame(width: screenWidth, height: screenHeight * 0.375)
.foregroundColor(.white)
}
VStack {
HStack {
self.appleIDButton
.frame(width: screenWidth - 24, height: 48)
.padding(.leading, 24)
}
.padding(.bottom, 16)
Text("Or")
.font(.system(size: 14))
.foregroundColor(Color("gray"))
.padding(.top, -16)
NavigationLink(destination: SignUpView()) {
HStack {
Spacer()
Text("Sign Up with email")
.font(.system(size: 17))
.fontWeight(.semibold)
.foregroundColor(.white)
Spacer()
}
.padding([.top, .bottom], 12)
}
.background(colors.primaryThemeColor, cornerRadius: 8)
.padding([.leading, .trailing], 24)
.padding(.bottom)
HStack {
Spacer()
Text("Already have an account?")
.foregroundColor(Color("gray"))
NavigationLink(destination: SignInView()) {
Text("Sign In")
.fontWeight(.semibold)
.foregroundColor(colors.primaryThemeColor)
}
Spacer()
}
.font(.system(size: 14))
}
.padding(.top, 24)
}
我的代码当前正在生成一个小于屏幕宽度一半并且正在触摸前沿的按钮。
当它显示在 SwiftUI View 中时,如何更改按钮的宽度以匹配正确的 View 约束?
最佳答案
您可以修改默认约束并设置新约束。
默认情况下,宽度需要大于 130。
ASAuthorizationAppleIDButton *appleButton = [[ASAuthorizationAppleIDButton alloc] init];
[appleButton addTarget:self action:@selector(handleSignInWithAppleIDButtonPress:) forControlEvents:UIControlEventTouchUpInside];
// Disable default width constraints
[appleButton.constraints enumerateObjectsUsingBlock:^(__kindof NSLayoutConstraint * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (obj.firstAttribute == NSLayoutAttributeWidth) {
obj.active = NO;
}
}];
// Set new ones
//[appleButton.widthAnchor constraintEqualToConstant:150].active = YES;
[appleButton.widthAnchor constraintEqualToConstant:40].active = YES;
[appleButton.heightAnchor constraintEqualToConstant:40].active = YES;
let appleButton = ASAuthorizationAppleIDButton()
authorizationButton.addTarget(self, action: #selector(handleLogInWithAppleIDButtonPress), for: .touchUpInside)
// Disable default width constraints
appleButton.constraints.forEach { (constraint) in
if (constraint.firstAttribute == .width) {
constraint.isActive = false
}
}
// Set new ones
//appleButton.widthAnchor.constraint(equalToConstant: 150).isActive = true
appleButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
关于ios - 如何更改 "Sign In with Apple"按钮的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57099148/