【问题标题】:How to resize UISwitch button?如何调整 UISwitch 按钮的大小?
【发布时间】:2023-09-18 12:54:01
【问题描述】:

我想调整我的UISwitch 按钮的大小,该按钮附加在UITableView 上。我在 google 上找到了一些帮助,并使用CGAffineTransformMakeScale 成功完成了此操作,但是当我更改此开关按钮的位置时,我遇到了一个问题,它具有自己的原始大小可能是因为它在桌面视图上,但我在@987654324 中调整了它的大小@ 代表。这就是我正在做的事情。

- (void)viewDidLoad{
 switchFB = [[UISwitch alloc] initWithFrame:CGRectMake(227, 8, 79, 27)];
switchFB.transform= CGAffineTransformMakeScale(0.7, 0.7);}

在单元格中用于索引路径处的行

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{`static NSString *CellIdentifier = @"SettingsCell";`

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }

请检查我做错的地方,如果我的程序不正确,请您建议我一些更好的方法来做到这一点。这对我来说会很棒。提前致谢。

【问题讨论】:

    标签: iphone ios xcode uitableview uiswitch


    【解决方案1】:

    我建议试用我编写的这个库。我有一个自述文件,可以很容易地弄清楚如何使用。 SwiftySwitch 它允许您将开关设置为任何您想要的大小。即使你不想使用这个库,你也可以看看我是如何制作自定义开关的。

    【讨论】:

      【解决方案2】:

      在 iOS 8 中,我使用自定义容器视图成功调整了 UISwitches 的大小。代码如下所示:

      @interface MyContainerView : UIView 
      
      @end
      
      @implementation MyContainerView
      
      - (void)layoutSubviews
      {
          [super layoutSubviews];
      
          // Center my subviews so the transform views properly
          CGPoint c = CGPointCenterOfRect(self.bounds);
          for (UIView * v in self.subviews)
          {
              v.center = c;
          }
      
      }
      @end
      
      
      UISwitch  * switchFB = [[UISwitch alloc] initWithFrame:CGRectZero];
      switchFB.transform= CGAffineTransformMakeScale(0.7, 0.7);
      
      CGSize s = switchFB.intrinsicContentSize;
      CGRect r = CGRectMake(0,0,s.width, s.height);
      MyContainerView * v = [[MyContainerView alloc] initWithFrame:r];
      
      [v addSubview:switchFB];
      

      容器视图的目的有两个: - 你掌握了可以正确自动布局的东西 - 内置自动布局尝试后,您可以子类化 layoutSubviews 并自动重新定位您的转换控件。

      请注意,UISwitch 在转换时确实会调整其内在内容大小,我使用它来设置容器视图的框架。

      【讨论】:

        【解决方案3】:

        试试这个

         UISwitch *mySwitch = [UISwitch new];
        mySwitch.transform = CGAffineTransformMakeScale(0.75, 0.75);
        

        【讨论】:

        • 你仔细阅读我的问题了吗,伙计,我正在按照你的建议做同样的事情。
        • 是的,您需要根据需要更改 0.75。这对我有用 mySwitch.transform = CGAffineTransformMakeScale(1.25, 1.1);我遇到了同样的问题,我用上述解决方案解决了。
        • 我在 view did load 方法中也做同样的事情,就像我提到的那样。 switchFB.transform= CGAffineTransformMakeScale(0.7, 0.7);} 它也是调整大小的开关按钮。
        • 是的,我已经尝试过了,它工作正常,但开关圆角被切割并且开关外观被破坏。任何建议。