首页 > 解决方案 > 使用 Interface Builder 创建了 UIButton。现在我想使用约束更改该按钮的位置和大小

问题描述

在此处输入图像描述

移除高度锚点后,下面是输出

在此处输入图像描述

精确常数截图

在此处输入图像描述

下面是视图控制器的设计。从 IB 截取屏幕截图。

在此处输入图像描述

我想更改使用 Interface Builder 创建的 UIButton 的位置和大小。我正在使用约束以编程方式进行。也学习约束。我已经编写了约束代码。请帮我。

let size = self.view.frame.size.height -
        (self.layer.frame.size.height + (self.navigationController?.navigationBar.frame.height)! + 20)  

channelShowBtn?.translatesAutoresizingMaskIntoConstraints = false
channelShowBtn!.topAnchor.constraint(equalTo:self.view.topAnchor , constant:(((20 + (navigationController?.navigationBar.frame.height)!) + self.layer.frame.height))).isActive = true
channelShowBtn!.heightAnchor.constraint(equalToConstant:size).isActive = true
channelShowBtn!.widthAnchor.constraint(equalToConstant:39).isActive = true

位置和大小应该改变,但实际上并没有改变。

标签: iosswift

解决方案


按钮约束

您可以从 xib 本身设置位置。

我在下面附上了图片,您可以根据需要设置宽度、高度、前导、尾随、顶部和底部约束。

按钮约束的图像

在这里你可以看到 Add New Constraints 选项在这里你可以根据需要定位按钮

制作高度约束出口:

@IBOutlet var heightConst: NSLayoutConstraint!

现在在视图中是否根据设备加载设置高度

if (UIDevice.current.screenType == .iPhones_5_5s_5c_SE){
        heightConst.constant = 400
    }else{
        heightConst.constant = 200
    }

将 UIDevice 扩展添加到您的代码(您也可以在此链接中找到:如何在 swift 中以编程方式检查 iphone 4 和 iphone 5 的屏幕尺寸):

 extension UIDevice {
    var iPhoneX: Bool {
        return UIScreen.main.nativeBounds.height == 2436
    }
    var iPhone: Bool {
        return UIDevice.current.userInterfaceIdiom == .phone
    }
    enum ScreenType: String {
        case iPhones_4_4S = "iPhone 4 or iPhone 4S"
        case iPhones_5_5s_5c_SE = "iPhone 5, iPhone 5s, iPhone 5c or iPhone SE"
        case iPhones_6_6s_7_8 = "iPhone 6, iPhone 6S, iPhone 7 or iPhone 8"
        case iPhones_6Plus_6sPlus_7Plus_8Plus = "iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus or iPhone 8 Plus"
        case iPhones_X_XS = "iPhone X or iPhone XS"
        case iPhone_XR = "iPhone XR"
        case iPhone_XSMax = "iPhone XS Max"
        case unknown
    }
    var screenType: ScreenType {
        switch UIScreen.main.nativeBounds.height {
        case 960:
            return .iPhones_4_4S
        case 1136:
            return .iPhones_5_5s_5c_SE
        case 1334:
            return .iPhones_6_6s_7_8
        case 1792:
            return .iPhone_XR
        case 1920, 2208:
            return .iPhones_6Plus_6sPlus_7Plus_8Plus
        case 2436:
            return .iPhones_X_XS
        case 2688:
            return .iPhone_XSMax
        default:
            return .unknown
        }
    }
}

推荐阅读