stackView swift中uibutton的自动布局/宽度问题

时间:2021-02-04 14:05:42

标签: ios swift uistackview

我有一个 UIScrollView,在它里面我有一个 UIStackView,我将它附加到几个 UIButton 中,现在当我附加一个 UIButton 时,大小会发生变化:\ 它也没有相同的大小 + 文本正在剪切:\我试图找到问题,但找不到:(。 这是我的代码:(必须说我使用故事板对 uiscrollview+uistackview 进行了自动布局)

这是自动布局的图片:Link https://imgur.com/a/DcIUBfA

这是它的外观图片:

enter image description here

import UIKit

class ByHashtags: UITableViewCell {
    
    @IBOutlet var hashTagOptionsStackView: UIStackView!
    @IBOutlet var selectedHashtagsStackView: UIStackView!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        
        self.preservesSuperviewLayoutMargins = false
        self.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
        self.layoutMargins = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
        
        insertOptionButtons()
        
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
    fileprivate func insertOptionButtons() {
        let button = UIButton(type: .custom)
        button.frame = CGRect(x: 0, y: 0, width: 100, height: 50)
        button.setTitle("#sport", for: .normal)
        button.titleLabel?.font =  UIFont(name: "Helvetica", size: 12)

        button.addTarget(self, action: #selector(insertIntoStackView(_:)), for: .touchUpInside)
        
        button.backgroundColor = #colorLiteral(red: 0.8394575715, green: 0.9233128428, blue: 0.9912871718, alpha: 1)
        button.setTitleColor(#colorLiteral(red: 0.3784077764, green: 0.6974633336, blue: 0.9678211808, alpha: 1), for: .normal)
        button.layer.cornerRadius = 12
        button.translatesAutoresizingMaskIntoConstraints = false
        
      
        let button2 = UIButton()
        button2.setTitle("#healing", for: .normal)
        button2.titleLabel?.font =  UIFont(name: "Helvetica", size: 12)

        button2.addTarget(self, action: #selector(insertIntoStackView(_:)), for: .touchUpInside)
        button2.backgroundColor = #colorLiteral(red: 0.8394575715, green: 0.9233128428, blue: 0.9912871718, alpha: 1)
        button2.setTitleColor(#colorLiteral(red: 0.3784077764, green: 0.6974633336, blue: 0.9678211808, alpha: 1), for: .normal)
        button2.layer.cornerRadius = 12

        button2.translatesAutoresizingMaskIntoConstraints = false
        
        let button3 = UIButton()
        button3.setTitle("#morningstory", for: .normal)
        button3.titleLabel?.font =  UIFont(name: "Helvetica", size: 12)

        
        button3.addTarget(self, action: #selector(insertIntoStackView(_:)), for: .touchUpInside)

        
        button3.backgroundColor = #colorLiteral(red: 0.8394575715, green: 0.9233128428, blue: 0.9912871718, alpha: 1)
        button3.setTitleColor(#colorLiteral(red: 0.3784077764, green: 0.6974633336, blue: 0.9678211808, alpha: 1), for: .normal)
        button3.layer.cornerRadius = 12

        button3.translatesAutoresizingMaskIntoConstraints = false
        
        hashTagOptionsStackView.alignment = .fill
        hashTagOptionsStackView.distribution = .fillEqually
        hashTagOptionsStackView.spacing = 10.0
        
        
        hashTagOptionsStackView.addArrangedSubview(button)
        hashTagOptionsStackView.addArrangedSubview(button2)
        hashTagOptionsStackView.addArrangedSubview(button3)
        
    }
    
    
    @objc func insertIntoStackView(_ sender: UIButton) {

        selectedHashtagsStackView.addArrangedSubview(sender)
    }
    
}

1 个答案:

答案 0 :(得分:0)

几个问题...

这一行:



public static void ImportPkcs8PrivateKey(this RSA rsa, ReadOnlySpan<byte> source, out int bytesRead)
{
    var assembly = typeof(RSA).Assembly;
    var derSequenceReader = assembly.GetType("System.Security.Cryptography.DerSequenceReader", true);

    var readerArgs = new[] { source.ToArray() };
    var reader = Activator.CreateInstance(
        derSequenceReader,
        BindingFlags.Instance | BindingFlags.NonPublic,
        null, readerArgs, null);

    var helperType = assembly.GetType("System.Security.Cryptography.RsaKeyBlobHelpers", true);
    var readPkcs8Blob = helperType.GetMethod(
        "ReadPkcs8Blob",
        BindingFlags.Static | BindingFlags.NonPublic);

    var methodArgs = new[] { reader, new RSAParameters() };
    readPkcs8Blob.Invoke(reader, methodArgs);

    // ReadPkcs8Blob() takes an RSAParameterr object as a 'ref'.
    var parameters = (RSAParameters)methodArgs[1];
    rsa.ImportParameters(parameters);
}

什么都不做,因为堆栈视图中的按钮使用自动布局。

如果您希望所有按钮的宽度均为 100,请设置堆栈视图的 button.frame = CGRect(x: 0, y: 0, width: 100, height: 50) 并为每个按钮设置宽度约束:

.distribution = .fill

对于您的滚动视图,确保将堆栈视图约束为滚动视图的 button.widthAnchor.constraint(equalToConstant: 100).isActive = true ,并将堆栈视图的高度约束为等于滚动视图的 Content Layout Guide 高度。

这是一个xib,它应该给你(接近)你想要的东西:

enter image description here

请注意,IB 不喜欢不完整的滚动视图布局,因此给每个堆栈视图一个内在内容大小“占位符”:

enter image description here

这是xib的源代码:

Frame Layout Guide

这是示例控制器和单元代码:

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="17701" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
    <device id="retina6_1" orientation="portrait" appearance="light"/>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17703"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <objects>
        <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
        <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" rowHeight="153" id="pPM-g6-WWs" customClass="ByHashtags" customModule="PanZoom" customModuleProvider="target">
            <rect key="frame" x="0.0" y="0.0" width="476" height="153"/>
            <autoresizingMask key="autoresizingMask"/>
            <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="pPM-g6-WWs" id="OXE-su-1dl">
                <rect key="frame" x="0.0" y="0.0" width="476" height="153"/>
                <autoresizingMask key="autoresizingMask"/>
                <subviews>
                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="By Hashtags" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="0iV-vu-7Zu">
                        <rect key="frame" x="16" y="10" width="103" height="20.5"/>
                        <fontDescription key="fontDescription" type="boldSystem" pointSize="17"/>
                        <nil key="textColor"/>
                        <nil key="highlightedColor"/>
                    </label>
                    <scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="JTS-SC-VrS" userLabel="ListOfHashTags">
                        <rect key="frame" x="16" y="40.5" width="444" height="40"/>
                        <subviews>
                            <stackView opaque="NO" contentMode="scaleToFill" placeholderIntrinsicWidth="200" placeholderIntrinsicHeight="30" translatesAutoresizingMaskIntoConstraints="NO" id="a09-ub-dWX">
                                <rect key="frame" x="0.0" y="0.0" width="200" height="40"/>
                            </stackView>
                        </subviews>
                        <color key="backgroundColor" red="0.99953407049999998" green="0.98835557699999999" blue="0.47265523669999998" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="a09-ub-dWX" firstAttribute="top" secondItem="nAx-F0-JiF" secondAttribute="top" id="1cC-PE-OeC"/>
                            <constraint firstItem="a09-ub-dWX" firstAttribute="height" secondItem="EAz-Mr-cfG" secondAttribute="height" id="Cmq-3F-kpO"/>
                            <constraint firstItem="a09-ub-dWX" firstAttribute="trailing" secondItem="nAx-F0-JiF" secondAttribute="trailing" id="DGV-I8-KLb"/>
                            <constraint firstAttribute="height" constant="40" id="YmK-dU-qj1"/>
                            <constraint firstItem="a09-ub-dWX" firstAttribute="bottom" secondItem="nAx-F0-JiF" secondAttribute="bottom" id="ieC-6z-MMz"/>
                            <constraint firstItem="a09-ub-dWX" firstAttribute="leading" secondItem="nAx-F0-JiF" secondAttribute="leading" id="t6l-u1-8P9"/>
                        </constraints>
                        <viewLayoutGuide key="contentLayoutGuide" id="nAx-F0-JiF"/>
                        <viewLayoutGuide key="frameLayoutGuide" id="EAz-Mr-cfG"/>
                    </scrollView>
                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Trending:" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="WCQ-ix-GRZ">
                        <rect key="frame" x="16" y="100.5" width="71" height="20.5"/>
                        <fontDescription key="fontDescription" type="system" weight="light" pointSize="17"/>
                        <nil key="textColor"/>
                        <nil key="highlightedColor"/>
                    </label>
                    <scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="u2n-IY-Fdc" userLabel="HashTagsOption">
                        <rect key="frame" x="103" y="90.5" width="357" height="40"/>
                        <subviews>
                            <stackView opaque="NO" contentMode="scaleToFill" placeholderIntrinsicWidth="200" placeholderIntrinsicHeight="30" translatesAutoresizingMaskIntoConstraints="NO" id="YxX-2S-tyP">
                                <rect key="frame" x="0.0" y="0.0" width="200" height="40"/>
                            </stackView>
                        </subviews>
                        <color key="backgroundColor" red="0.45009386540000001" green="0.98132258650000004" blue="0.4743030667" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="YxX-2S-tyP" firstAttribute="leading" secondItem="Uns-Dw-jnK" secondAttribute="leading" id="4ZO-sx-0DL"/>
                            <constraint firstAttribute="height" constant="40" id="Aj5-oj-mtC"/>
                            <constraint firstItem="YxX-2S-tyP" firstAttribute="top" secondItem="Uns-Dw-jnK" secondAttribute="top" id="DE6-FD-VA3"/>
                            <constraint firstItem="YxX-2S-tyP" firstAttribute="trailing" secondItem="Uns-Dw-jnK" secondAttribute="trailing" id="Gha-rq-BV7"/>
                            <constraint firstItem="YxX-2S-tyP" firstAttribute="bottom" secondItem="Uns-Dw-jnK" secondAttribute="bottom" id="KXv-PA-vML"/>
                            <constraint firstItem="YxX-2S-tyP" firstAttribute="height" secondItem="6Sx-2o-tss" secondAttribute="height" id="Riu-eV-99K"/>
                        </constraints>
                        <viewLayoutGuide key="contentLayoutGuide" id="Uns-Dw-jnK"/>
                        <viewLayoutGuide key="frameLayoutGuide" id="6Sx-2o-tss"/>
                    </scrollView>
                </subviews>
                <constraints>
                    <constraint firstItem="u2n-IY-Fdc" firstAttribute="top" secondItem="JTS-SC-VrS" secondAttribute="bottom" constant="10" id="3r3-Ai-onp"/>
                    <constraint firstItem="JTS-SC-VrS" firstAttribute="leading" secondItem="OXE-su-1dl" secondAttribute="leading" constant="16" id="880-ZB-ECh"/>
                    <constraint firstAttribute="bottom" relation="greaterThanOrEqual" secondItem="u2n-IY-Fdc" secondAttribute="bottom" constant="10" id="Kwo-76-H59"/>
                    <constraint firstAttribute="trailing" secondItem="u2n-IY-Fdc" secondAttribute="trailing" constant="16" id="PbP-Ha-Y2v"/>
                    <constraint firstItem="0iV-vu-7Zu" firstAttribute="leading" secondItem="OXE-su-1dl" secondAttribute="leading" constant="16" id="Pt2-nX-hef"/>
                    <constraint firstItem="WCQ-ix-GRZ" firstAttribute="leading" secondItem="OXE-su-1dl" secondAttribute="leading" constant="16" id="SKF-CH-ixU"/>
                    <constraint firstAttribute="trailing" secondItem="JTS-SC-VrS" secondAttribute="trailing" constant="16" id="T0G-Am-A6U"/>
                    <constraint firstItem="u2n-IY-Fdc" firstAttribute="leading" secondItem="WCQ-ix-GRZ" secondAttribute="trailing" constant="16" id="YCK-v4-CBa"/>
                    <constraint firstItem="WCQ-ix-GRZ" firstAttribute="centerY" secondItem="u2n-IY-Fdc" secondAttribute="centerY" id="da9-N8-o27"/>
                    <constraint firstItem="JTS-SC-VrS" firstAttribute="top" secondItem="0iV-vu-7Zu" secondAttribute="bottom" constant="10" id="f5p-e1-IaC"/>
                    <constraint firstItem="0iV-vu-7Zu" firstAttribute="top" secondItem="OXE-su-1dl" secondAttribute="top" constant="10" id="tOy-83-JJx"/>
                </constraints>
            </tableViewCellContentView>
            <connections>
                <outlet property="hashTagOptionsStackView" destination="YxX-2S-tyP" id="y5U-sR-n3E"/>
                <outlet property="selectedHashtagsStackView" destination="a09-ub-dWX" id="HV5-3W-Hvo"/>
            </connections>
            <point key="canvasLocation" x="152.17391304347828" y="84.040178571428569"/>
        </tableViewCell>
    </objects>
</document>

点击第一个按钮后的结果(我给了滚动视图背景颜色,以便于查看框架):

enter image description here